Swapping Numbers

C program to swap two numbers.


Method 1:

Using only two variables

#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
clrscr();
printf("Enter two numbers a and b: ");
scanf("%d %d",&a,&b);
a+=b;
b=a-b;
a-=b;
printf("\nAfter swapping, a: %d and b: %d",a,b);
return 0;
}


Method 2:

Using three variables

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,temp;
clrscr();
printf("Enter two numbers a and b: ");
scanf("%d %d",&a,&b);
temp=a;
a=b;
b=temp;
printf("\nAfter swapping, a: %d and b: %d",a,b);
getch();
}


Method 3:

Using bitwise operator

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter two numbers a and b: ");
scanf("%d %d",&a,&b);
a=a^b;
b=a^b;
a=a^b;
printf("\nAfter swapping, a: %d and b: %d",a,b);
getch();
}