ProgrammingHardCapgemini · Infosys pattern

How many times is fun called in total when fun(6) is evaluated?

How many times is fun called in total when fun(6) is evaluated?
Function fun(Integer n)
    if (n <= 2)
        return 1
    end if
    return fun(n - 1) + fun(n - 2) + fun(n - 3)
End Function
  1. A. 27
  2. B. 13
  3. C. 25
  4. D. 17

Correct answer: C. 25

Let C(n) be the number of calls. C(n) = 1 + C(n-1) + C(n-2) + C(n-3), with C(0) = C(1) = C(2) = 1. Then C(3) = 4, C(4) = 7, C(5) = 13, C(6) = 1 + 13 + 7 + 4 = 25. The return value, fun(6) = 17, is the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic