ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (g is a global variable.)

What will be the output of the following pseudocode? (g is a global variable.)
Integer g = 0
Function f(Integer n)
    if (n == 0)
        return 0
    end if
    g = g + n
    Integer r = f(n - 1)
    return r + g
End Function

Print f(4), g
  1. A. 30 10
  2. B. 20 10
  3. C. 40 4
  4. D. 40 10

Correct answer: D. 40 10

All the additions to g happen on the way down: g becomes 4, 7, 9, 10 before any call returns. Every level then reads g after its recursive call, when g is already 10. So f(1) = 0 + 10, f(2) = 10 + 10, f(3) = 30, f(4) = 40, and g = 10. 30 = 4 + 7 + 9 + 10 assumes each level adds the value g had when that level started.

More Pseudocode and Code Tracing questions

Exams that ask this topic