C Program to swap numbers using pointer

Simple C program to swap two numbers using pointer. We know, pointer is a variable that store the address of another variables. To swap two numbers, first we store address of both numbers into two pointer to integer variables. Here pointer to integer variables are p and q. After that we change the value of the address of first number and second number.
 
/* C program to swap two numbers using pointer */
#include<stdio.h>
int main()
{
 int first,second,*p,*q;
 printf("Enter first number: ");
 scanf("%d",&first);
 printf("Enter second number: ");
 scanf("%d",&second);
 printf("Number before swapping: \n");
 printf("First= %d\n",first);
 printf("Second = %d\n",second);
 p=&first;
 q=&second;
 int temp=*p;
 *p=*q;
 *q=temp;
 printf("Number after swapping: \n");
 printf("First= %d\n",first);
 printf("Second = %d\n",second);
 return 0;

/* End of the program */
 

Another C program to swap to numbers using function
 
/* C program to swap two numbers using pointer */
#include<stdio.h>
void SwapNumbers(int *first, int *second)
{
 int temp=*first;
 *first=*second;
 *second=temp;
}
int main()
{
 int first,second;
 printf("Enter first number: ");
 scanf("%d",&first);
 printf("Enter second number: ");
 scanf("%d",&second);
 printf("Number before swapping: \n");
 printf("First= %d\n",first);
 printf("Second = %d\n",second);
 
 SwapNumbers(&first,&second);
 
 printf("Number after swapping: \n");
 printf("First= %d\n",first);
 printf("Second = %d\n",second);
 return 0;
}
/* End of the program */





Popular posts from this blog