ProgrammingVery hardTCS Digital · Capgemini

What will be the output of the following pseudocode? (/ truncates toward zero and mod keeps the sign of the dividend (as in C))

What will be the output of the following pseudocode? (/ truncates toward zero and mod keeps the sign of the dividend (as in C))
Integer x = -123, r = 0
while (x != 0)
    r = r * 10 + x mod 10
    x = x / 10
end while
Print r
  1. A. -321
  2. B. 123
  3. C. -3
  4. D. -312

Correct answer: A. -321

With C-style arithmetic, −123 mod 10 = −3 and −123 / 10 = −12, so the digits come out negative: r = −3, −32, −321. The sign is kept automatically: −321.

More Pseudocode and Code Tracing questions

Exams that ask this topic