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
  1. A1, 1, 2, 1, 1, 2, 3
  2. B3, 2, 1, 1, 2, 1, 1
  3. 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).
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. What does the following function fib return when called as fib(10)?
  2. When the following function c is called as c(4, 2), how many times is c called, including the first call?
  3. ⊕ is bitwise exclusive OR. What are the values of x and y after the following program runs?
  4. x and y are 8-bit unsigned integers. << and >> are logical shifts: vacated bits are filled with 0, and bits shifted out of the 8 bits are discarded. ∨ is bitwise OR. What is the value of y after the following program runs?
  5. ∧ is bitwise AND. What is the value of c after the following program runs?