ProgrammingHardProduct company OA

What is printed?

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

Correct answer: D. 3 5

calls counts the non-base calls and the base case hands back the count and resets it, so each top-level call reports its own depth: 3, then 5. Without the reset the second would print 8.

More C Programming questions

Exams that ask this topic