ProgrammingHardInfosys SP · TCS Digital

What will be the output of the following pseudocode? ((b & 1) is evaluated before == ; & is AND, << and >> are shifts)

What will be the output of the following pseudocode? ((b & 1) is evaluated before == ; & is AND, << and >> are shifts)
Integer a = 13, b = 11, p = 0, adds = 0
while (b > 0)
    if (b & 1 == 1)
        p = p + a
        adds = adds + 1
    end if
    a = a << 1
    b = b >> 1
end while
Print p, adds
  1. A. 143 4
  2. B. 143 11
  3. C. 130 3
  4. D. 143 3

Correct answer: D. 143 3

Shift-and-add multiplication: 11 = 1011 in binary, so p = 13 + 26 + 104 = 143, using one addition per 1-bit of b: 3. Output 143 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic