ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.)

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.)
Integer n = 45, c = 0
while (n > 0)
    n = n & (n - 1)
    c = c + 1
end while
Print c
  1. A. 6
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: B. 4

n & (n - 1) clears the lowest set bit, so the loop runs once per 1-bit. 45 = 101101₂ has four 1s.

More Pseudocode and Code Tracing questions

Exams that ask this topic