Contact Learn C
Copy

Program 187:Swap two numbers using Pointers

Program 187:
 
 #include<stdio.h>
void swap(int *,int*);
main( )
{
int a,b;
printf("Enter a and b values\n");
scanf("%d%d",&a,&b);
printf ("Values before Swap\na=%d\nb=%d\n",a,b ) ;
swap(&a,&b ) ;
printf ("Values after Swap\na=%d\nb=%d\n",a,b ) ;
}
void swap( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}


Explanation:

  1. To understand this, it is very important to know what is a function. You can refer to my website by visiting this URL https://beginnerlanguage.blogspot.com/p/functions.html. 
  2. int a,b;
    printf("Enter a and b values\n");
    scanf("%d%d",&a,&b);
    printf ("Values before Swap\na=%d\nb=%d\n",a,b ) ;
    

    Here we declared 2 variables a and b and took user input. And let's say a=25 and b=100. And printed them on screen before we swap them.

  3. swap(&a,&b ) ;
    Now we are calling the function swap by passing 2 parameters a and b using reference &. 

  4. void swap( int *x, int *y )
    {
    int t ;
    t = *x ;
    *x = *y ;
    *y = t ;
    }
    In this method, we are doing the same which we used here and the explanation is also the same https://www.cprograms4future.com/p/swap-numbers-with-two-variables.html

  5. The only difference is , here we used pointers. Pointers will work based on reference. Now we no need to return back any values as the values changes in method swap will automatically reflect in a and b values. As a is *x and b is *y. 
  6. printf ("Values after Swap\na=%d\nb=%d\n",a,b ) ;
    Finally, we are printing swapped values of a and b.
What is Pointer??
You can open my All C Programs app and go through the explanation I gave under interview questions on "What is a Pointer?".
Then you will understand better on this concept.

Output:








 

No comments:

Post a Comment

Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide