GATE Computer ScienceHardGATE CS (PYQ pattern)

int x = 0; void q(int n) { if (n > 0) { x += n; q(n - 1); printf("%d ", x); if (n > 2) q(n - 2); } } What does q(4) print?

  1. A. 10 10 10 10 12 12
  2. B. 4 7 9 10 9 10
  3. C. 10 10 10 11 11 14 14
  4. D. 10 10 10 10 12 13

Correct answer: C. 10 10 10 11 11 14 14

x is global, so each print shows the running total: q(4) first adds 4, 3, 2, 1 (x = 10) before any print, giving 10 10 10, then q(1) from q(3) adds 1 (11, printed twice on the way out), and q(2) from q(4) adds 2 and 1 (x = 14, printed twice).

More Programming and Data Structures (GATE) questions

Exams that ask this topic