C | Operators | Question 18

In C, two integers can be swapped using minimum
(A) 0 extra variable
(B) 1 extra variable
(C) 2 extra variable


Answer: (A)

Explanation: We can swap two variables without any extra variable using bitwise XOR operator ‘^’. Let X and Y be two variables to be swapped. Following steps swap X and Y.

  X = X ^ Y;
  Y = X ^ Y;
  X = X ^ Y;

See http://en.wikipedia.org/wiki/XOR_swap_algorithm

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.