ProgrammingHardTCS NQT · Accenture pattern

How many numbers are printed when fun(5) is called?

How many numbers are printed when fun(5) is called?
Function fun(Integer n)
    if (n <= 0)
        return
    end if
    fun(n - 1)
    Print n
    fun(n - 2)
End Function
  1. A. 15
  2. B. 7
  3. C. 12
  4. D. 8

Correct answer: C. 12

Let P(n) be the count. P(n) = P(n-1) + 1 + P(n-2), with P(0) = P(-1) = 0. So P(1) = 1, P(2) = 2, P(3) = 4, P(4) = 7, P(5) = 12 (Fibonacci numbers minus 1).

More Pseudocode and Code Tracing questions

Exams that ask this topic