Programmers...Swapping Algorithm!

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.
• Philippines
20 Dec 06
This is a good answer. Thank you! I really appreciate it. I will choose your response as the best response.
@mythmoh (3994)
• United States
19 Dec 06
let we take a=2 and b=3 then a=a+b b=a-b a=a-b so a=2+3=5 b=5-3=2 a=5-2=3
• 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.