Program to Swap Two Numbers using Temporary Variable

Following is the program to swap two numbers with the help of a temporary variable.

#include<iostream.h>
#include<conio.h>

int main()
{
	int a,b,x;

	cout<<"Enter a and b:\n";
	cin>>a>>b;
	cout<<"Before swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b= "<<b<<endl;
	{
		x=a;
		a=b;
		b=x;
		cout<<"After swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b= "<<b<<endl;
	}
getch();
return 0;
}

Output:

Enter a and b:
23 33
Before swapping
Value of a= 23
Value of b= 33
After swapping
Value of a= 33
Value of b= 23

Program to Swap Two Numbers without using Temporary Variable

Following is the program to swap two numbers without the help of any temporary variable.

#include<iostream.h>
#include<conio.h>

int main()
{
	int a,b;

	cout<<"Enter a and then b:\n";
	cin>>a>>b;
	cout<<"\nBefore swapping\nValue of a= "<<a<<"\nValue of b= "<<b<<endl;
	cout<<"\nAfter swapping\nValue of a= "<<b<<"\nValue of b= "<<a<<endl;

getch();
return 0;
}

Output:

Enter a and then b:
23 33
Before swapping
Value of a= 23
Value of b= 33
After swapping
Value of a= 33
Value of b= 23