ProgrammingHardAccenture · Cognizant pattern

What will be the output? (A do-while loop runs its body once before checking the condition; / is integer division.)

What will be the output? (A do-while loop runs its body once before checking the condition; / is integer division.)
Integer x = 0, c = 0, y = 10, k = 0
do
    c = c + 1
    x = x + 5
while (x < 0)
do
    k = k + 1
    y = y / 2
while (y > 0)
Print c, x, k
  1. A. 0 0 4
  2. B. 0 0 3
  3. C. 1 5 3
  4. D. 1 5 4

Correct answer: D. 1 5 4

The first loop's condition is false from the start, but a do-while still runs once: c = 1, x = 5. The second loop takes y through 10 → 5 → 2 → 1 → 0, which is 4 passes. Treating them as while loops gives 0 0 for the first loop.

More Pseudocode and Code Tracing questions

Exams that ask this topic