ProgrammingVery hardProduct company OA

What is printed?

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

Correct answer: B. 6 9

total is static, so it persists across both top-level calls and every recursive frame. First call f(3): total goes 0->3->5->6 as n descends 3,2,1, then f(0) returns total=6. Second call f(2): total continues from 6, goes 6->8->9 as n descends 2,1, then f(0) returns total=9. Output: 6 9.

More C Programming questions

Exams that ask this topic