ProgrammingHardTCS NQT · Accenture

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer n = 10, steps = 0
while (n != 1)
    if (n mod 3 == 0)
        n = n / 3
    else
        n = n + 1
    end if
    steps = steps + 1
end while
Print steps
  1. A. 3
  2. B. 8
  3. C. 7
  4. D. 9

Correct answer: B. 8

Trace: 10 → 11 → 12 → 4 → 5 → 6 → 2 → 3 → 1, eight updates. Reading the else branch as n − 1 gives 10 → 9 → 3 → 1 (3 steps), stopping before the last step 3 → 1 gives 7, and counting the 9 values visited instead of the moves gives 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic