ProgrammingHardGoldman Sachs OA · Infosys SP

What will be the output of the following pseudocode? (& is bitwise AND, >> is right shift)

What will be the output of the following pseudocode? (& is bitwise AND, >> is right shift)
Integer s = 0, x, t
for (each i from 1 to 16)
    x = i
    t = 0
    while ((x & 1) == 0)
        x = x >> 1
        t = t + 1
    end while
    s = s + t
end for
Print s
  1. A. 16
  2. B. 8
  3. C. 15
  4. D. 31

Correct answer: C. 15

t is the number of trailing zero bits of i, i.e. the power of 2 in i. Summed over 1 to 16 it is the power of 2 in 16!: 8 + 4 + 2 + 1 = 15.

More Pseudocode and Code Tracing questions

Exams that ask this topic