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)); }
  1. A. 6
  2. B. 10
  3. C. 4
  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

Exams that ask this topic