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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


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