Swapping without third variable

Swapping is interchanging the variable values.
For eg: if a=4 and b=5
after swapping a=5 and b=4. This swapping is done by a temporary variable. Now we're going to swap the values without using a temporary variable. Here's the program


#include < iostream.h >
void main()
{
int a=4, b=5;
a=a+b;
b=a-b;
a=a-b;
cout < < a < < b;
}

How it works?


first a=4 b=5
then a=a+b
now a will become 9.
then b=a-b will execute b=9-4=5
then a=a-b=9-5=4
that's all number swapped
NOTE:
you can do this operation by multiplication&division,x-or operators instead of using addition operators. i.e.,
a=a*b;
b=a/b;
a=a/b;
otherwise using x-or operators
a=a^b;
b=a^b;
a=a^b;

Related Posts