Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Swaping values of two variable without temporary variable

4.83/5 (18 votes)
11 Mar 2010CPOL 1  
I don't know whether these type of tips are allowed or not. But after having experience of core algorithm-base technical interview I thought I should share question I was asked in my interview.They asked me to show all methods I know to swap values of two variables.I Tried my level best...
I don't know whether these type of tips are allowed or not. But after having experience of core algorithm-base technical interview I thought I should share question I was asked in my interview.

They asked me to show all methods I know to swap values of two variables.

I Tried my level best to do it:
//1st method
a -= b;
b += a;         
a = (b - a);    

//2nd methos
a = b + a - (b = a)

//3rd method
a ^= b ^= a ^= b;

//4th method
a -= b += a -= b = -b;

//5th method
//Assuming a and b are none zero and int
a=a*b;
b=a/b;
a=a/b;

//6th method
//Assuming a and b are binary types
a %= b %= a %= b;


Note : All one line codes are compiler dependent only.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)