ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int f(int n) {
int r;
if (n == 0) return 0;
r = f(n - 1);
n--;
return r + n + 1;
}
int main(void) { printf("%d", f(4)); }- A. 6
- B. 10
- C. 4
- D. 9
Correct answer: B. 10
Despite the local n-- after the recursive call, each frame still adds its ORIGINAL n (since n was decremented only in the local frame's own copy, and r + n + 1 uses the post-decrement n which equals original n-1, plus 1, netting the original n). Tracing: f(0)=0. f(1): r=f(0)=0, n becomes 0, return 0+0+1=1. f(2): r=f(1)=1, n becomes 1, return 1+1+1=3. f(3): r=f(2)=3, n becomes 2, return 3+2+1=6. f(4): r=f(3)=6, n becomes 3, return 6+3+1=10.
More C Programming questions
- What is printed? c int f(int n) { if (n <= 0) return 1; return f(n - 1) + f(n - 1); } int main(void) { printf("%d", f(3)); }
- What is printed? c int count = 0; void f(int n) { count++; if (n <= 1) return; f(n - 1); f(n - 2); } int main(void) { f(4); printf("%d"…
- What is printed? c int f(int n, int d) { if (d > n) return 0; if (n % d == 0) return d + f(n, d + 1); return f(n, d + 1); } int main(void)…
- What is printed? Assume no stack overflow for this depth. c int f(int n) { if (n == 0) return 0; if (n % 3 == 0) return 1 + f(n - 3)…
- What is printed? c int f(int n) { if (n == 0) return 0; int r = f(n - 1); printf("%d ", n); return r; } int main(void) { int x = f(4)…
- What is printed? c union U { char c; int i; double d; }; printf("%zu", sizeof(union U));