The methods that we are going to use in this program are:
Using third variable
Without using third variable
Using X-OR operator
Using simple statement
Program:
//C program to swap two numbers using four different methods.
#include <stdio.h>
int main()
{
int a,b,t;
printf(" Enter value of A ? ");
scanf("%d",&a);
printf(" Enter value of B ? ");
scanf("%d",&b);
printf("\n Before swapping : A= %d, B= %d",a,b);
/****first method using third variable*/
t=a;
a=b;
b=t;
printf("\n After swapping (First method) : A= %d, B= %d\n",a,b);
/****second method without using third variable*/
a=a+b;
b=a-b;
a=a-b;
printf("\n After swapping (second method): A= %d, B= %d\n",a,b);
/****Third method using X-Or */
a^=b;
b^=a;
a^=b;
printf("\n After swapping (third method) : A= %d, B= %d\n",a,b);
/****fourth method (single statement)*/
a=a+b-(b=a);
printf("\n After swapping (fourth method): A= %d, B= %d\n",a,b);
return 0;
}
Output
Enter value of A ? 100
Enter value of B ? 200
Before swapping : A= 100, B= 200
After swapping (First method) : A= 200, B= 100
After swapping (second method): A= 100, B= 200
After swapping (third method) : A= 200, B= 100
After swapping (fourth method): A= 100, B= 200
The methods that we are going to use in this program are:
Program:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer