Thread: swapping
View Single Post
  #1 (permalink)  
Old 03-02-2008, 04:39 AM
Chinmoy's Avatar   
Chinmoy Chinmoy is offline
Programming Professional
 
Join Date: Feb 2008
Location: where heaven meets earth
Posts: 305
Rep Power: 7
Chinmoy has a spectacular aura aboutChinmoy has a spectacular aura about
Default swapping

here is a really simple program to swap 2 numbers without using a third variable.

say you have 2 numbers a and b;
now what you do is add a in b.
then save b-a in a.now save b-a in b.


{
int a=3,b=2;
cout<<"Initially to "<<a<<" "<<b;
{
b+=a;
a=b-a;
b=b-a;
}
cout<<"Swapped to "<<a<<" "<<b;
}

take care of the sequence.b takes a+b. now we put b in a by a=(b-a);meaning a=b(initial value).so now a=b-initial.so b=b-a..
simple.
Reply With Quote

Sponsored Links