ProgrammingHardGoldman Sachs OA · Infosys SP

What will be the output of the following pseudocode? (^ is XOR, >> is right shift)

What will be the output of the following pseudocode? (^ is XOR, >> is right shift)
Integer s = 0, g
for (each i from 0 to 7)
    g = i ^ (i >> 1)
    s = s + g
    if (i == 5)
        Print g
    end if
end for
Print s
  1. A. 5 28
  2. B. 6 28
  3. C. 7 36
  4. D. 7 28

Correct answer: D. 7 28

i ^ (i >> 1) is the Gray code of i: 0, 1, 3, 2, 6, 7, 5, 4. For i = 5 it is 101 ^ 010 = 111 = 7. The 8 codes are a rearrangement of 0 to 7, so s = 28: 7 28.

More Pseudocode and Code Tracing questions

Exams that ask this topic