GATE Computer ScienceHardGATE CS (PYQ pattern)

int g(int n) { static int s = 0; s += n; if (n > 0) { g(n - 1); s += n; } return s; } int main() { int x = g(3); int y = g(2); printf("%d %d", x, y); } What is printed?

  1. A. 12 15
  2. B. 12 14
  3. C. 12 18
  4. D. 15 18

Correct answer: C. 12 18

s accumulates n before the recursive call and n after it; one call g(3) adds 3+2+1 twice = 12. The static is not reset, so g(2) adds 2*(2+1) = 6 more, giving 18.

More Programming and Data Structures (GATE) questions

Exams that ask this topic