GATE Computer ScienceVery hardGATE CS (PYQ pattern)
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 does p(6) print, and what is their sum?
- A. 28 numbers, sum 407
- B. 40 numbers, sum 506
- C. 20 numbers, sum 341
- D. 28 numbers, sum 347
Correct answer: A. 28 numbers, sum 407
Let N(n) be the count printed by p(n): N(0) = 0 and N(n) = 2 + N(n - 1), plus N(n - 2) when n is even and n > 2. So N(1) = 2, N(2) = 4, N(3) = 6, N(4) = 8 + 4 = 12, N(5) = 14, N(6) = 16 + 12 = 28. Every call p(k) with k > 0 prints k and 10k (11k together); adding 11k over all calls gives 407. Making only the outermost call p(6) branch into p(4) (and that p(4) not branching again) gives 20 numbers.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- 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…
- int t(int n) { return n == 0 ? 0 : n % 3 + 10 t(n / 3); } What is t(97) + t(t(7))?