# Programmers...Swapping Algorithm!

@jessie_marcelo (146)

Philippines

December 18, 2006 7:20pm CST

I wanna swap the values of two variables: A and B. How can I do it without using a third variable?
Please give me a good algorithm. Thanks!

3 responses

@WebGal (48)

• United States

19 Dec 06

This is a well-known puzzle. The solution is to use the 'exclusive-or' operator; in C, C++, java and Perl (at least, and probably other languages I'll not stop to verify now), exclusive-or is coded with the caret, '^'.
To swap the values of A and B, code the following three statements:
A=A^B;
B=A^B;
A=A^B;
Note, however, that this only works when A and B are integers of the same length. It will not work when A and B are different sizes or when they are floating-point values.

@jessie_marcelo (146)

• Philippines

20 Dec 06

This is a good answer. Thank you! I really appreciate it. I will choose your response as the best response.

@swaroop_sv2003 (531)

• India

19 Dec 06

Let A =2 and B =3
To swap values of A and B
A = A+B
So A =5
B = A-B
So B becomes 2
A = A-B
So A becomes 3
Thus final result is A = 3 and B =2
Thus values are swapped.