ProgrammingHardTCS NQT · Accenture pattern

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 = 20, steps = 0
while (n != 1)
    if (n mod 2 == 0)
        n = n / 2
    else
        n = n - 1
    end if
    steps = steps + 1
end while
Print n, steps
  1. A. 1 4
  2. B. 1 5
  3. C. 0 5
  4. D. 1 6

Correct answer: B. 1 5

20->10->5->4->2->1, taking exactly 5 steps (halving when even, subtracting 1 when odd) before n reaches 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic