Saturday, January 29, 2011

Swapping two variables in c++

Swapping of variables means that changing the values of variable with each other's value.

Swapping two integer values


Method 1 (using third variable )
--------

******************* Start of Program ************************

#include"iostream.h"
#include"conio.h"

void main()
{
clrscr();
int a,b,c;
cout<<"Enter value of a :: ";
cin>>a;
cout<<"\nEnter value of b :: ";
cin>>b;


c=a;
a=b;
b=c;

cout<<"\nNow value of a is "<cout<<"\nNow value of b is "<
getch();
}
******************* END ************************



Method 2 ( without using third variable )
--------
* Main advantage of this program is that it uses less memory

******************* Start of Program ************************

#include"iostream.h"
#include"conio.h"

void main()
{
clrscr();
int a,b;
cout<<"Enter value of a :: ";
cin>>a;
cout<<"\nEnter value of b :: ";
cin>>b;


a=a+b;
b=a-b;
a=a-b;

cout<<"\nNow value of a is "<cout<<"\nNow value of b is "<
getch();
}

******************* END ************************