Consider the following sequence of instructions: a = a ⊕ b, b = a ⊕ b, a = b ⊕…
2005
Consider the following sequence of instructions:
a = a ⊕ b,
b = a ⊕ b,
a = b ⊕ a.
This sequence
- A.
retains the value of a and b
- B.
complements the value of a and b
- C.
swap a and b
- D.
negates values of a and b
Attempted by 165 students.
Show answer & explanation
Correct answer: C
This sequence implements the XOR swap algorithm.
Initially, let a = x and b = y.
After step 1, a becomes x ⊕ y.
In step 2, b becomes (x ⊕ y) ⊕ y = x.
Finally, step 3 updates a to x ⊕ (x ⊕ y) = y.
Thus, the values of a and b are swapped.
A video solution is available for this question — log in and enroll to watch it.