Archive for the ‘C Programming’ Category

How to swap two variables without a temp variable?

Tuesday, February 10th, 2009

This was one of those weird questions that got popped at me during a recent recruitment process. I tried to attempt it using XOR logic which I had read at a c programming tutorial page. The XOR truth table is unique in the sense that when both inputs are opposite (i.e a=true/ON and b=false/OFF), then the output is true or ON. Otherwise, the output is false or OFF.

The truth table for XOR (Exclusive OR) is shown below:

A B O/P
0 0 0
1 0 1
0 1 1
1 1 0

The solution is as follows.

Assume int a = 5; and int b = 3;

Now to swap them using XOR, one has to do the following

a = a xor b; // 5 ^ 3 = 6
b = a xor b; // 6 ^ 3 = 5
a = a xor b; //6 ^ 5 = 3

That’s it! we have swapped the two variables without using a temp variable. We saved resources when we could have easily wasted a few more bytes! Now, there’s an other way to do it. Why would you need a XOR when you could do it with the common ‘+’? Well, I needed some assistance to figure out it was the same logic to do a swap with the common and more preferred additive ‘+’ operator. Here is the solution.

a = a + b; //a = 8 (sum of the two variables)
b = a - b; // b = 8 - 3 = 5
a = a - b; //a = 8 - 5 = 3

Phew! At the end of it, I could not but wonder what weird questions get popped at you during an interview. Hope you enjoy your next one!



Advertise here!


My Networks
Follow me on twitter!
View Madan Gopal Revoor's profile on LinkedIn