ProgrammingHardInfosys · 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 = 2309, c = 0
while (n > 0)
    c = c + (n & 1)
    n = n >> 1
end while
Print c
  1. A. 4
  2. B. 5
  3. C. 11
  4. D. 3

Correct answer: A. 4

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

More Pseudocode and Code Tracing questions

Exams that ask this topic