ProgrammingVery hardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (Print writes its value followed by a space.)

What will be the output of the following pseudocode? (Print writes its value followed by a space.)
Function f(n)
    If n <= 0 Then Return 0
    Print n
    r = f(n - 2) + f(n - 3)
    Print n
    Return r + 1
End Function
Print f(5)
  1. A. 4 5 3 1 1 3 2 2 5
  2. B. 5 3 1 1 3 2 2 5 4
  3. C. 5 3 1 2 4
  4. D. 5 3 1 1 3 2 2 5 0

Correct answer: B. 5 3 1 1 3 2 2 5 4

The call tree is f(5) -> f(3) [-> f(1), f(0)] and f(2) [-> f(0), f(-1)]; each real call prints n before and after its children. Tracing the pre- and post-prints gives the sequence shown, and the final return value counts the calls with n > 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic