Swapping of 2 numbers Without 3rd Variable

This is a simple  Program in C++ / C for Swapping of 2 variable without third variable. This is a part of Mumbai University MCA Colleges. 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.

Hope this Program is useful to you in some sense or other. Keep on following this blog for more Mumbai University MCA College Programs. Happy Programming and Studying.

No comments:

Post a Comment