ProgrammingModerateInfosys SP · TCS NQT

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 x = 255, y = 256, c1 = 0, c2 = 0
while (x > 0)
    x = x & (x - 1)
    c1 = c1 + 1
end while
while (y > 0)
    y = y & (y - 1)
    c2 = c2 + 1
end while
Print c1, c2
  1. A. 8 9
  2. B. 255 256
  3. C. 8 1
  4. D. 1 8

Correct answer: C. 8 1

x & (x − 1) clears the lowest 1-bit, so each loop runs once per 1-bit: 255 = 1111 1111 has 8, and 256 = 1 0000 0000 has just 1. Output 8 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic