Swap Two Numbers / Variables using Pointer

 C Program to Swap Two Numbers / Variables using Pointer

#include<stdio.h>
 

/*passed address of variables from main to swap function. So we need variable container that can store the     address of integer variables i.e Integer Pointers*/
void swap(int *n1, int *n2)
{
   int temp;
   temp = *n1;
   *n1 = *n2;        /*
address of first number will be collected in “num1” pointer variable */
   *n2 = temp;      /*second number will be collected in “num2” pointer variable*/
}

int main()
 {
   int n1, n2;


 /*accept two numbers using scanf statement*/
   printf("Enter 1st number : \n");
   scanf("%d", &n1);
   printf("Enter 2nd number : \n");
   scanf("%d", &n2);
 

/*pass the address of both variables to the function. Parameter passing is called as Pass by Pointer*/
   swap(&n1, &n2);

   printf("First number  : %d\n", n1);
   printf("Second number : %d\n", n2);

}

Related Posts