Programming Basics (Pseudocode Tracing)
When the following procedure p is called as p(3), what sequence of values is output?
○p(integer: n)
if (n > 0)
p(n − 1)
output n
p(n − 1)
endif
- A1, 1, 2, 1, 1, 2, 3
- B3, 2, 1, 1, 2, 1, 1
- C1, 2, 1, 3, 1, 2, 1
Show answer and explanation
Answer: C. 1, 2, 1, 3, 1, 2, 1
p(1) runs p(0), outputs 1 and runs p(0), so it outputs just "1". p(2) runs p(1), outputs 2 and runs p(1), giving "1, 2, 1". p(3) gives "1, 2, 1" from p(2), then 3, then "1, 2, 1" from p(2) again: 1, 2, 1, 3, 1, 2, 1. There are 2³ − 1 = 7 outputs, the same as the order of disk numbers moved in a three-disk Tower of Hanoi.
- A. This is the order when the output comes after both recursive calls.
- B. This is the order when the output comes before the recursive calls.
- C. Correct. The output of p(2), then 3, then the output of p(2).
Continue: 9 more Programming Basics (Pseudocode Tracing) questions