ProgrammingVery hardProduct company OA

What will be the output of the following pseudocode? ('ref' parameters are passed by reference; ^ is bitwise XOR; arrays are indexed from 0.)

What will be the output of the following pseudocode? ('ref' parameters are passed by reference; ^ is bitwise XOR; arrays are indexed from 0.)
Procedure swap(ref Integer a, ref Integer b)
    a = a ^ b
    b = a ^ b
    a = a ^ b
End Procedure
Integer arr[3] = {5, 7, 9}
swap(arr[0], arr[2])
swap(arr[1], arr[1])
Print arr[0], arr[1], arr[2]
  1. A. 9 0 5
  2. B. 9 7 5
  3. C. 5 0 9
  4. D. 9 7 9

Correct answer: A. 9 0 5

The first call swaps 5 and 9 normally. In the second call a and b refer to the SAME element: a = a ^ b sets it to 7 ^ 7 = 0, and every later XOR keeps it 0. So the middle element is destroyed: 9 0 5. That is why an XOR swap must check that the two references differ.

More Pseudocode and Code Tracing questions

Exams that ask this topic