ProgrammingHardProduct company OA · Infosys pattern

What will be the output of the following pseudocode? (& is bitwise AND.)

What will be the output of the following pseudocode? (& is bitwise AND.)
Integer total = 0
for (i = 1 to 15)
    Integer n = i
    while (n != 0)
        n = n & (n - 1)
        total = total + 1
    end while
end for
Print total
  1. A. 15
  2. B. 30
  3. C. 32
  4. D. 64

Correct answer: C. 32

n & (n − 1) clears the lowest set bit, so the inner loop runs once per 1-bit. Across 0..15 (all 4-bit patterns) each bit position is 1 in half of the 16 numbers: 4 × 8 = 32 one-bits, and 0 contributes nothing. '15' counts numbers, not bits.

More Pseudocode and Code Tracing questions

Exams that ask this topic