Jumat, 04 Desember 2015

When is the right time to use

1. Struct
In C#, a structure is a value type data type. we use Struct when we want to make a single variable hold related data of various data types. The struct keyword is used for creating a structure. Structures are used to represent a record. Suppose you want to keep track of your books in a library


2. Pointer/reference
A pointer is a variable whose value is the address of another variable, we use Pointer when we want to direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address


3. Function
Functions will generally require a prototype. we use Function when we want compiler  function will return, what the function will be called, as well as what arguments the function can be passed. Function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four.

4. Array
Array will specifies the type of the elements and the number of elements required by an array as follows .You use an array when you need to reference a list of objects or values. You use a while loop when you need to repeat a block of code based on a condition. Example when you have 1000 numbers, if you don't use arrays. you will find it's hard to sort these numbers...

=Write an example that uses combination all of items above.=

1. Pointer to Array of Structure stores the Base address of the Structure array.
void main()
{
struct Cricket *ptr = match;   // By default match[0]
for(i=0;i<4;i++)
    {
    printf("\nMatch : %d",i+1);[
    printf("\n%s Vs %s",ptr->team1,ptr->team2);
    printf("\nPlace : %s",ptr->ground);

    if(match[i].result == 1)
        printf("nWinner : %s",ptr->team1);
    else
        printf("nWinner : %s",ptr->team1);
    printf("\n");

    // Move Pointer to next structure element
    ptr++;
    }
}


2. Example of Pointer And Functions
Program to swap two number using call by reference.

 /* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
  int num1=5,num2=10;
  swap(&num1,&num2);  /* address of num1 and num2 is passed to swap function */
  printf("Number1 = %d\n",num1);
  printf("Number2 = %d",num2);
  return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}


Rabu, 02 Desember 2015

Rotation and Flipping Using SDL

Here adding more functionality to the texture class. The render function now takes in a rotation angle, a point to rotate the texture around, and a SDL flipping enum.

Like with clipping rectangles, give the arguments default values in case you want to render the texture without rotation or flipping.

//Texture wrapper class
class LTexture
{
    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path );

        //Deallocates texture
        void free();

        //Set color modulation
        void setColor( Uint8 red, Uint8 green, Uint8 blue );

        //Set blending
        void setBlendMode( SDL_BlendMode blending );

        //Set alpha modulation
        void setAlpha( Uint8 alpha );
     
        //Renders texture at given point
        void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );

        //Gets image dimensions
        int getWidth();
        int getHeight();

    private:
        //The actual hardware texture
        SDL_Texture* mTexture;

        //Image dimensions
        int mWidth;
        int mHeight;
};

Before enter the main loop. declare variables to keep track of the rotation angle and flipping type.

       //Main loop flag
            bool quit = false;

            //Event handler
            SDL_Event e;

            //Angle of rotation
            double degrees = 0;

            //Flip type
            SDL_RendererFlip flipType = SDL_FLIP_NONE;

In the event loop, increment/decrement the rotation with the a/d keys and change the type of flipping with the q,w, and e keys.

   //Handle events on queue
                while( SDL_PollEvent( &e ) != 0 )
                {
                    //User requests quit
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    else if( e.type == SDL_KEYDOWN )
                    {
                        switch( e.key.keysym.sym )
                        {
                            case SDLK_a:
                            degrees -= 60;
                            break;
                         
                            case SDLK_d:
                            degrees += 60;
                            break;

                            case SDLK_q:
                            flipType = SDL_FLIP_HORIZONTAL;
                            break;

                            case SDLK_w:
                            flipType = SDL_FLIP_NONE;
                            break;

                            case SDLK_e:
                            flipType = SDL_FLIP_VERTICAL;
                            break;
                        }
                    }
                }

Sound Effects and Music Using DSL

//Using SDL, SDL_image, SDL_mixer, standard IO, and strings
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <stdio.h>
#include <string>

SDL_mixer is a library use to make audio playing easier (because it can get complicated). to set it up just like set up SDL_image. Like before, it's just a matter of having the headers files, library files, and binary files in the right place with your compiler configured to use them.

     //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                }

                 //Initialize SDL_mixer
                if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
                {
                    printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
                    success = false;
                }

To initialize SDL_mixer need to call Mix_OpenAudio. The first argument sets the sound frequency, and 44100 is a standard frequency that works on most systems. The second argument determines the sample format, which again here using the default. The third argument is the number of hardware channels, and here using 2 channels for stereo. The last argument is the sample size, which determines the size of the chunks use when playing sound

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load prompt texture
    if( !gPromptTexture.loadFromFile( "21_sound_effects_and_music/prompt.png" ) )
    {
        printf( "Failed to load prompt texture!\n" );
        success = false;
    }

    //Load music
    gMusic = Mix_LoadMUS( "21_sound_effects_and_music/beat.wav" );
    if( gMusic == NULL )
    {
        printf( "Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

Here load our splash texture and sound.
To load music call Mix_LoadMUS and to load sound effect call Mix_LoadWAV. 

    //Load sound effects
    gScratch = Mix_LoadWAV( "21_sound_effects_and_music/scratch.wav" );
    if( gScratch == NULL )
    {
        printf( "Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }
 
    gHigh = Mix_LoadWAV( "21_sound_effects_and_music/high.wav" );
    if( gHigh == NULL )
    {
        printf( "Failed to load high sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    gMedium = Mix_LoadWAV( "21_sound_effects_and_music/medium.wav" );
    if( gMedium == NULL )
    {
        printf( "Failed to load medium sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    gLow = Mix_LoadWAV( "21_sound_effects_and_music/low.wav" );
    if( gLow == NULL )
    {
        printf( "Failed to load low sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    return success;
}

In the event loop, play a sound effect when the 1, 2, 3, or 4 keys are pressed. The way to play a Mix_Chunk is by calling Mix_PlayChannel. The first argument is the channel you want to use to play it
 //Handle key press
                    else if( e.type == SDL_KEYDOWN )
                    {
                        switch( e.key.keysym.sym )
                        {
                            //Play high sound effect
                            case SDLK_1:
                            Mix_PlayChannel( -1, gHigh, 0 );
                            break;
                         
                            //Play medium sound effect
                            case SDLK_2:
                            Mix_PlayChannel( -1, gMedium, 0 );
                            break;
                         
                            //Play low sound effect
                            case SDLK_3:
                            Mix_PlayChannel( -1, gLow, 0 );
                            break;
                         
                            //Play scratch sound effect
                            case SDLK_4:
                            Mix_PlayChannel( -1, gScratch, 0 );
                            break;

play/pause the music on a 9 keypress and stop the music on a 0 keypress.

When the 9 key pressed first check if the music is not playing with Mix_PlayingMusic. If it isn't,start the music with Mix_PlayMusic. The first argument is the music play and the last argument is the number of times to repeat it. Negative 1 is a special valu to loop it until it is stopped.

 case SDLK_9:
                            //If there is no music playing
                            if( Mix_PlayingMusic() == 0 )
                            {
                                //Play the music
                                Mix_PlayMusic( gMusic, -1 );
                            }
                            //If music is being played
                            else
                            {
                                //If the music is paused
                                if( Mix_PausedMusic() == 1 )
                                {
                                    //Resume the music
                                    Mix_ResumeMusic();
                                }
                                //If the music is playing
                                else
                                {
                                    //Pause the music
                                    Mix_PauseMusic();
                                }
                            }
                            break;
                         
                            case SDLK_0:
                            //Stop the music
                            Mix_HaltMusic();
                            break;
                        }
                    }

Time Capabilites Using SDL

//Using SDL, SDL_image, SDL_ttf, standard IO, strings, and string streams
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>
#include <sstream>

Before enter the main loop to declare some variables.  pay attention to is the startTime variable (which is an Unsigned integer that's 32bits) and the timeText variable which is a string stream.

 //Main loop flag
            bool quit = false;

            //Event handler
            SDL_Event e;

            //Set text color as black
            SDL_Color textColor = { 0, 0, 0, 255 };

            //Current time start time
            Uint32 startTime = 0;

            //In memory text stream
            std::stringstream timeText;

There's a function called SDL_GetTicks which returns the time since the program started in milliseconds. For this demo,  be having a timer that restarts every time  press the return key.

 //While application is running
            while( !quit )
            {
                //Handle events on queue
                while( SDL_PollEvent( &e ) != 0 )
                {
                    //User requests quit
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    //Reset start time on return keypress
                    else if( e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_RETURN )
                    {
                        startTime = SDL_GetTicks();
                    }
                }
using our string stream. First call str with an empty string to initialize it to be empty. Then treat it like cout and print to it "Milliseconds since start time " and the current time minus the relative start time so it will print the time since last started the timer.

        //Set text to be rendered
                timeText.str( "" );
                timeText << "Milliseconds since start time " << SDL_GetTicks() - startTime;

How to Rendering text from true type Fonts Using SDL

One way to render text with SDL is with the extension library SDL_ttf. SDL_ttf allows you to create images from TrueType fonts which use here to create textures from font text.

//Using SDL, SDL_image, SDL_ttf, standard IO, math, and strings
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>

#include <cmath>

To use SDL_ttf, you have to set up the SDL_ttf extension library just like you would set up SDL_image. Like before, it's just a matter of having the headers files, library files, and binary files in the right place with your compiler configured to use them.

//The window be rendering to
SDL_Window* gWindow = NULL;

//The window renderer
SDL_Renderer* gRenderer = NULL;

//Globally used font
TTF_Font *gFont = NULL;

//Rendered texture

LTexture gTextTexture;

For this and future tutorials, using a global font for our text rendering. In SDL_ttf, the data type for fonts is TTF_Font.


and also have a texture which will be generated from the font.

 //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                }

                 //Initialize SDL_ttf
                if( TTF_Init() == -1 )
                {
                    printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
                    success = false;

                }

Just like SDL_image, we have to initialize it or the font loading and rendering functions won't work properly.start up SDL_ttf using TTF_init. We can check for errors using TTF_GetError().

void close()
{
    //Free loaded images
    gTextTexture.free();

    //Free global font
    TTF_CloseFont( gFont );
    gFont = NULL;

    //Destroy window    
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;

    //Quit SDL subsystems
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

}

In our clean up function, we want to free the font using TTF_CloseFont. We also want to quit the SDL_ttf library with TTF_Quit to complete the clean up.

How To Color Keying Using SDL

When rendering multiple images on the screen, having images with transparent backgrounds is usually necessary. Fortunately SDL provides an easy way to do this using color keying.

//Texture wrapper class
class LTexture
{
    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path );

        //Deallocates texture
        void free();

        //Renders texture at given point
        void render( int x, int y );

        //Gets image dimensions
        int getWidth();
        int getHeight();

    private:
        //The actual hardware texture
        SDL_Texture* mTexture;

        //Image dimensions
        int mWidth;
        int mHeight;
};

Color key the cyan (light blue) colored background and render it on top of this background:

(foo.png)

Next, color key the image with SDL_SetColorKey before creating a texture from it. The first argument is the surface  to color key, the second argument covers whether to enable color keying, and the last argument is the pixel to color key with.

    //The final texture
    SDL_Texture* newTexture = NULL;

    //Load image at specified path
    SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
    if( loadedSurface == NULL )
    {
        printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
    }
    else
    {
        //Color key image
        SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );

=Here are the image loading functions in action.=

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load Foo' texture
    if( !gFooTexture.loadFromFile( "10_color_keying/foo.png" ) )
    {
        printf( "Failed to load Foo' texture image!\n" );
        success = false;
    }
    
    //Load background texture
    if( !gBackgroundTexture.loadFromFile( "10_color_keying/background.png" ) )
    {
        printf( "Failed to load background texture image!\n" );
        success = false;
    }

    return success;
}

=Here are the image loading functions in action.=

void close()
{
    //Free loaded images
    gFooTexture.free();
    gBackgroundTexture.free();

    //Destroy window    
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;

    //Quit SDL subsystems
    IMG_Quit();
    SDL_Quit();
}


How to getting an Image on the Screen using SDL

1. How to getting an Image on the Screen using SDL

Here some global variables.

//The window be rendering to
SDL_Window* gWindow = NULL;
 
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image will load and show on the screen
SDL_Surface* gHelloWorld = NULL;

In the load media function load our image using SDL_LoadBMP. SDL_LoadBMP takes in the path of a bmp file and returns the loaded surface. If the function returns NULL, that means it failed so print to the console an error using SDL_GetError.

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load splash image
    gHelloWorld = SDL_LoadBMP( "02_getting_an_image_on_the_screen/hello_world.bmp" );
    if( gHelloWorld == NULL )
    {
        printf( "Unable to load image %s! SDL Error: %s\n", "02_getting_an_image_on_the_screen/hello_world.bmp", SDL_GetError() );
        success = false;
    }

    return success;
}

void close()
{
    //Deallocate surface
    SDL_FreeSurface( gHelloWorld );
    gHelloWorld = NULL;

    //Destroy window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}


Make sure to get into the habit of having your pointers point to NULL when they're not pointing to anything.

int main( int argc, char* args[] )
{
    //Start up SDL and create window
    if( !init() )
    {
        printf( "Failed to initialize!\n" );
    }
    else
    {
        //Load media
        if( !loadMedia() )
        {
            printf( "Failed to load media!\n" );
        }
        else
        {
            //Apply the image
            SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );


Stdarg

A function may be called with a varying number of arguments of  varying types.  The include file <stdarg.h> declares a type va_list and defines three macros for stepping through a list of arguments whose number and types are not known to the called function.

stdarg.h Types
Name           :   va_list
Description       :  type for iterating arguments


Macro functions
va_start            :  Initialize a variable argument list (macro )
va_arg              :  Retrieve next argument (macro )
va_end             :  End using variable argument list (macro )
va_copy           : Copy variable argument list (macro )

 - va_start()
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.

-  va_arg()
The va_arg() macro expands to an expression that has the type and value of the next argument in the call

- va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function.
 
-va_copy()
The va_copy() macro copies the (previously initialized) variable argument list src to dest.

-The function "foo" takes a string of format characters and prints out the argument associated with each format character based on the type.

=Example=

  #include <stdio.h>
  #include <stdarg.h>

       void
       foo(char *fmt, ...)
       {
           va_list ap;
           int d;
           char c, *s;

           va_start(ap, fmt);
           while (*fmt)
               switch (*fmt++) {
               case 's':              /* string */
                   s = va_arg(ap, char *);
                   printf("string %s\n", s);
                   break;
               case 'd':              /* int */
                   d = va_arg(ap, int);
                   printf("int %d\n", d);
                   break;
               case 'c':              /* char */
                   /* need a cast here since va_arg only
                      takes fully promoted types */
                   c = (char) va_arg(ap, int);
                   printf("char %c\n", c);
                   break;
               }
           va_end(ap);
       }

Senin, 30 November 2015

File

File is an object on the computer that stores data
There are 2 kinds of file in general:
-Text file (source code, plain text, html files, mosts of configuration files, etc)
-Binary file (mosts audio and video file formats, graphics file formats, compressed files, mosts of office formats, etc)


(-)Type

For files you want to read or write, you need a file pointer:
FILE *fp;

(-)Functions
Reading from or writing to a file in C requires 3 basic steps:
-Open the file.
-Do all the reading or writing.
-Close the file.

-Opening a file:
In order to open a file, use the function fopen(). Use it as:
fp = fopen(filename, mode);

-Reading from or writing to a file:
Once a file has been successfully opened, you can read from it using fscanf() or write to it using fprintf(). These functions work just like scanf() and printf(), except they require an extra first parameter, a FILE * for the file to be read/written.

-Closing a file:
When done with a file, it must be closed using the function fclose().
To finish our example, we'd want to close our input and output files:
fclose(ifp);
fclose(ofp);

=Example=

Write a C program to read name and marks of n number of students from user and store them in a file
#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","w"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}

Selasa, 24 November 2015

Structures


Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.

Syntax of structure

struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
    char name[50];
    int cit_no;
    float salary;
};
This declaration above creates the derived data type struct person.

Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other variable or pointer.
#include <stdio.h>
#include <string.h>
 
struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( ) {

   struct Books Book1;        /* Declare Book1 of type Book */
   struct Books Book2;        /* Declare Book2 of type Book */
 
   /* book 1 specification */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali"); 
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* book 2 specification */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* print Book1 info */
   printBook( Book1 );

   /* Print Book2 info */
   printBook( Book2 );

   return 0;
}

void printBook( struct Books book ) {

   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);
} 
When the above code is compiled and executed, it produces the following result 
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Example program for array of structures in C

This program is used to store and access “id, name and percentage” for 3 students. Structure array is used in this program to store and display records for many students. You can store “n” number of students record by declaring structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc.

#include <stdio.h>
#include <string.h>

struct student 
{
     int id;
     char name[30];
     float percentage;
};

int main() 
{
     int i;
     struct student record[2];

     // 1st student's record
     record[0].id=1;
     strcpy(record[0].name, "Raju");
     record[0].percentage = 86.5;

     // 2nd student's record         
     record[1].id=2;
     strcpy(record[1].name, "Surendren");
     record[1].percentage = 90.5;

     // 3rd student's record
     record[2].id=3;
     strcpy(record[2].name, "Thiyagu");
     record[2].percentage = 81.5;

     for(i=0; i<3; i++)
     {
         printf("     Records of STUDENT : %d \n", i+1);
         printf(" Id is: %d \n", record[i].id);
         printf(" Name is: %s \n", record[i].name);
         printf(" Percentage is: %f\n\n",record[i].percentage);
     }
     return 0;
}

Output:

Records of STUDENT : 1 Id is: 1 Name is: Raju Percentage is: 86.500000
Records of STUDENT : 2 Id is: 2 Name is: Surendren Percentage is: 90.500000
Records of STUDENT : 3 Id is: 3 Name is: Thiyagu Percentage is: 81.500000

Example program for declaring many structure variable in C


In this program, two structure variables “record1″ and “record2″ are declared for same structure and different values are assigned for both structure variables. Separate memory is allocated for both structure variables to store the data.


#include <stdio.h>
#include <string.h>

struct student 
{
     int id;
     char name[30];
     float percentage;
};

int main() 
{
     int i;
     struct student record1 = {1, "Raju", 90.5};
     struct student record2 = {2, "Mani", 93.5};

     printf("Records of STUDENT1: \n");
     printf("  Id is: %d \n", record1.id);
     printf("  Name is: %s \n", record1.name);
     printf("  Percentage is: %f \n\n", record1.percentage);

     printf("Records of STUDENT2: \n");
     printf("  Id is: %d \n", record2.id);
     printf("  Name is: %s \n", record2.name);
     printf("  Percentage is: %f \n\n", record2.percentage);

     return 0;
}

Output:

Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000

Pointer And Reference

What is Pointer?

pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration:


type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:

int         /* pointer to an integer */
double   /* pointer to a double */
float      /* pointer to a float */
char      /* pointer to a character */

As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined :

#include <stdio.h>

int main () {

   int  var1;
   char var2[10];

   printf("Address of var1 variable: %x\n", &var1  );
   printf("Address of var2 variable: %x\n", &var2  );

   return 0;
}

When the above code is compiled and executed, it produces the following result 

Address of var2 variable: bff5a3f6

What Are Pointer And Reference?
Pointers and reference are essentially variables that hold memory addresses as their values. You learned before about the various different data types such as: intdouble, and char. Pointers and references hold the addresses in memory of where you find the data of the various data types that you have declared and assigned. The two mechanisms, pointers and references, have different syntax and different traditional uses.

Declaring Pointer And Reference


When declaring a pointer to an object or data type, you basically follow the same rules of declaring variables and data types that you have been using, only now, to declare a pointer of SOMETYPE, you tack on an asterix * between the data type and its variable.

SOMETYPE* sometype;  int* x; 

To declare a reference, you do the exact same thing you did to declare a pointer, only this time, rather than using an asterix *, use instead an ampersand &.

SOMETYPE& sometype; 

int& x;

As you probably have already learned, spacing in C++ does not matter, so the following pointer declarations are identical:

SOMETYPE*  sometype;
SOMETYPE * sometype;
SOMETYPE  *sometype;

The following reference declarations are identical as well:

SOMETYPE&  sometype;
SOMETYPE & sometype;
SOMETYPE  &sometype;


The Null Pointer

Remember how you can assign a character or string to be null? If you don't remember, check out HERE. The null character in a string denotes the end of a string, however, if a pointer were to be assigned to the null pointer, it points to nothing. The null pointer is often denoted by 0 or null. The null pointer is often used in conditions and/or in logical operations.


#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );
 
   return 0;
}


When the above code is compiled and executed, it produces the following result 
The value of ptr is 0

If pointer px is NOT null, then it is pointing to something, however, if the pointer is null, then it is pointing to nothing. The null pointer becomes very useful when you must test the state of a pointer, whether it has a value or not.

To check for a null pointer, you can use an 'if' statement as follows
if(ptr)     /* succeeds if p is not null */
if(!ptr)    /* succeeds if p is null */

Returning Pointers and References from Functions

When declaring a function, you must declare it in terms of the type that it will return, for example:


int MyFunc(); // returns an int 
SOMETYPE MyFunc(); // returns a SOMETYPE 

int* MyFunc(); // returns a pointer to an int 
SOMETYPE *MyFunc(); // returns a pointer to a SOMETYPE 
SOMETYPE &MyFunc(); // returns a reference to a SOMETYPE 

The declaration of a function that returns a pointer or a reference should seem relatively logical. The above piece of code shows how to basically declare a function that will return a reference or a pointer.


SOMETYPE *MyFunc(int *p) 
{ 
   ... 
   ... 
   return p; 
} 

SOMETYPE &MyFunc(int &r) 
{ 
  ... 
  ... 
  return r; 
}

Within the body of the function, the return statement should NOT return a pointer or a reference that has the address in memory of a local variable that was declared within the function, else, as soon as the function exits, all local variables ar destroyed and your pointer or reference will be pointing to some place in memory that you really do not care about. Having a dangling pointer like that is quite inefficient and dangerous outside of your function.
However, within the body of your function, if your pointer or reference has the address in memory of a data type, struct, or class that you dynamically allocated the memory for, using the new operator, then returning said pointer or reference would be reasonable.


SOMETYPE *MyFunc()  //returning a pointer that has a dynamically 
{           //allocated memory address is proper code 
   int *p = new int[5]; 
   ... 
   ... 
   return p; 
} 


Returning Pointers to an Array

you can return a pointer to an array by specifying the array's name without an index.If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:

int * myFunction()
{
.
.
.
}

Sabtu, 17 Oktober 2015

Function on C Programming

What is Function?

Function is a feature or tool used to wrap one or several computational processes and supporting information, to complete an action or process of computing based on its usefulness.
From the definition above, it can be concluded that the function is a special tool that can take action to solve specific problems. The point? The intent of the sentence can be understood from the use of the function. Still confused? Here the example of a function that must have been frequently used in writing programs in C language, printf (), getchar (), scanf () is a function that we can use to solve or handle a process, and each of these functions has a way of working  :)
Declaration and Usage
A function declared as below

return_type function_name (parameter_declaration, [second_parameter_if_any)
{
  declarations_variable;
  statements;
}

return_type is the data type of a function declared. This data type is the main thing that must be considered in making a function or a function, Okay, then how to use the functions that we make? In general, if we want to use a function that we have previously made, we simply call the name of the function and the function will only work by itself. So we do not have to worry about how the function that implement what we are told, because the C language already has its own way to handle it, which is important for us is how to make a function properly.




Note the declaration and use of function in the program code above. Authors declare two functions with different return type to be used in the program, for a declaration written before function main ().
Then, consider the declaration of a function is  different . The main difference in the type of data and functions that define the parameters of the function.
At the time of declaring the function, the variable naming parameter is not an important part, the most important is the data type of the parameter. Okay,  code for the function that has been declared previously in the lower part (after the function main ()). Naming the variable parameters to be used.

How Recursion Works with example in C

Recursion is a process that calls the process back. Recursion in C language functions are realized in the form of one or more instructions are dialing instructions to call a function that returns either directly or indirectly. Function which is called the recursive function. I use software C Compiler Dev C++
Example of recursion in C Programming

Write a C program to find sum of first n natural numbers using recursion. Example :

















Output :


in the program c on top, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to a function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
The following explanation above recursion :

sum(10)
=10+sum(9)
=10+9+sum(8)
=10+9+8+sum(7)
=10+9+8+7+sum(6)
=10+9+8+7+6+sum(5)
=10+9+8+7+6+5+sum(4)
=10+9+8+7+6+5+4+sum(3)
=10+9+8+7+6+5+4+3+sum(2)
=10+9+8+7+6+5+4+3+2+sum(1)
=10+9+8+7+6+5+4+3+2+1+0
=10+9+8+7+6+5+4+3+2+1
=10+9+8+7+6+5+4+3+3
=10+9+8+7+6+5+4+6
=10+9+8+7+6+5+10
=10+9+8+7+6+15
=10+9+8+7+21
=10+9+8+28
=10+9+36
=10+45
=55
   
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to 0, there is no recursive call and recursion ends.