Tuesday, 3 June 2014

0

C Program 13: To Swap Two Numbers Using Pointers

  • Tuesday, 3 June 2014
  • IndianBooktuber
  • Share
  • Aim: Swap two numbers using pointers.
    Following is the code:
    //To swap two numbers using pointers
    #include<stdio.h>
    #include<conio.h>
    void swap(int *a, int *b)
    {
         int temp;
         temp = *a;
         *a=*b;
         *b=temp;
        // printf ("The value of a is: %d \n ", *a );
         //printf("The value of b is: %d\n ", * b);
    }
    void main()
    {
         int *a, *b;
         printf("enter the two numbers: ");
         scanf("%d%d", &a, &b);
         swap (&a,&b);
         printf ("The value of a is: %d \n", a );
         printf("The value of b is: %d \n ", b);
         getch();
    }

    Theory: We will perform the swapping in function swap. So, the function swap has two arguments - *a and *b. An * before a means a is actually the value at address of a. So, if the value at address of a is 53, *a would take up that value.
    Now, we use the basic swapping operation. We will put the *a into a temporary variable and then *b into *a and again temp into *b. This concludes the swapping. Now, if we want to print the resulting numbers in the swap function itself, we will need to use *a and *b in printf statement instead of a and b. This is because we want to print the value at a and b. If we don't do that, address of the a and b would be printed or some garbage value.
    Now, coming back to main function, we must make sure that we pass address of a and b (&a, &b) to the swap function else we won't receive the correct output.

    0 Responses to “C Program 13: To Swap Two Numbers Using Pointers”

    Post a Comment

    Subscribe