ProgrammingVery hardTCS NQT Advanced · Capgemini

What will be the output of the following pseudocode? (the static s keeps its value between calls; in f(n - 1) + s the call is evaluated first)

What will be the output of the following pseudocode? (the static s keeps its value between calls; in f(n - 1) + s the call is evaluated first)
Function f(Integer n)
    static Integer s = 0
    s = s + n
    if (n <= 1)
        return s
    end if
    return f(n - 1) + s
End Function
Print f(4)
  1. A. 30
  2. B. 40
  3. C. 20
  4. D. 10

Correct answer: B. 40

s is shared by all calls and is read only after f(n − 1) returns, by which time it has become 4 + 3 + 2 + 1 = 10. So f(1) = 10, f(2) = 20, f(3) = 30, f(4) = 40. Reading s before the call gives the trap 30.

More Pseudocode and Code Tracing questions

Exams that ask this topic