Open In App

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
(D) 4 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

Article Tags :