Swapping of 2 numbers Without 3rd Variable

Ram Pothuraju
This is a simple  Program in C++ / C for Swapping of 2 variable without third variable. . This type of questions are often asked in Interviews.


SWAPPING OF 2 VARIABLES WITHOUT 3RD VARIABLE.

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

 void main() 

int a=11,b=20; 
b=(a+b)-(a=b);      
cout<<"B is "<<b<<endl<<"A is "<<a; 
getch(); 
}

Here in this program, we use a single statement to swap the 2 numbers. 
in the statement b=(a+b)-(a=b);  we 1st add the 2 variable and then assign b to a, which is then subtracted from the sum of the 2 variable and assigned to b.

There are many more variations to swapping the variables without the 3rd variable.

Tags

Post a Comment

0Comments

Post a Comment (0)