ProgrammingHardTCS NQT · Infosys · Capgemini pattern

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 n = 1958, c = 0
while (n > 0)
    c = c + (n & 1)
    n = n >> 1
end while
Print c
  1. A. 8
  2. B. 7
  3. C. 6
  4. D. 10

Correct answer: B. 7

This loop counts set bits (Hamming weight) of 1958 by repeatedly checking the last bit (n & 1) and shifting right. 1958 in binary is 11110100110, which has 7 set bits.

More Pseudocode and Code Tracing questions

Exams that ask this topic