ProgrammingHardAccenture · Cognizant pattern

What will be the output? (A static variable keeps its value between calls and is initialised only once. The two calls in Print are evaluated left to right.)

What will be the output? (A static variable keeps its value between calls and is initialised only once. The two calls in Print are evaluated left to right.)
Function fun(Integer n)
    static Integer c = 0
    c = c + n
    if (n > 1)
        fun(n - 1)
    end if
    return c
End Function

Print fun(4) + fun(2)
  1. A. 10
  2. B. 33
  3. C. 13
  4. D. 23

Correct answer: D. 23

fun(4) adds 4 + 3 + 2 + 1 to c, so c = 10 and fun(4) returns 10. c is NOT reset, so fun(2) adds 2 + 1 and returns 13. 10 + 13 = 23. Treating c as an ordinary local gives 10 + 3 = 13.

More Pseudocode and Code Tracing questions

Exams that ask this topic