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?
- A. 12 15
- B. 12 14
- C. 12 18
- 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.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- void p(int n) { if (n == 0) return; printf("%d ", n); p(n - 1); printf("%d ", n 10); if (n % 2 == 0 && n > 2) p(n - 2); } How many numbers…
- void f(int x, int y, int z) { x = y + z; y = x - z; z = x; } int main() { int a = 1, b = 2, c = 3; f(&a, &b, c); f(&b, &a, c); f(&a, &a…
- int h(int n) { return n == 0 ? 0 : 2 h(n / 10) + n % 10; } What is h(2593)?
- int A(int m, int n) { if (m == 0) return n + 1; if (n == 0) return A(m - 1, 1); return A(m - 1, A(m, n - 1)); } How many calls to A…
- int f(int n); int g(int n) { return n <= 0 ? 1 : f(n - 1) + g(n - 2); } int f(int n) { return n <= 0 ? 0 : g(n - 1) + n; } What does f(6)…
- void r(char s) { if (s[0] == 0 || s[1] == 0) { printf("%s", s); return; } printf("%c%c", s[1], s[0]); r(s + 2); printf("%c", s[0]); } What…