ProgrammingVery hardGoldman Sachs OA · Infosys SP

What will be the output of the following pseudocode? (^ is XOR, & is AND)

What will be the output of the following pseudocode? (^ is XOR, & is AND)
Integer s = 0, x, p
for (each i from 1 to 20)
    x = i
    p = 0
    while (x > 0)
        p = p ^ 1
        x = x & (x - 1)
    end while
    s = s + p
end for
Print s
  1. A. 11
  2. B. 9
  3. C. 10
  4. D. 20

Correct answer: C. 10

x & (x − 1) removes one set bit each time, so p ends as the parity of the number of 1-bits. s counts the numbers 1 to 20 with an odd number of 1's: 1, 2, 4, 7, 8, 11, 13, 14, 16, 19 = 10.

More Pseudocode and Code Tracing questions

Exams that ask this topic