ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int f(int n) {
    static int depth = 0;
    depth++;
    if (n <= 1) return depth;
    int a = f(n - 1);
    int b = f(n - 2);
    return a + b;
}
int main(void) {
    int r = f(4);
    printf("%d", r);
}
  1. A. 32
  2. B. 5
  3. C. 24
  4. D. 9

Correct answer: A. 32

depth is shared by every call and counts calls made so far, and each base case returns that count. Calls in order: f4(1), f3(2), f2(3), f1(4) → 4, f0(5) → 5, so f2 = 9; f1(6) → 6, so f3 = 15; f2(7) has f1(8) → 8 and f0(9) → 9, so 17; f4 = 15 + 17 = 32. '9' is the number of calls, and '5' the Fibonacci-style answer.

More C Programming questions

Exams that ask this topic