ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
int f(int n) {
    static int s = 0;
    s += n;
    if (n > 0) f(n - 1);
    return s;
}
...
printf("%d ", f(3));
printf("%d", f(3));
  1. A. 6 12
  2. B. 3 3
  3. C. 6 6
  4. D. 6 18

Correct answer: A. 6 12

All recursive calls share the one static s. The first f(3) adds 3 + 2 + 1 + 0, and the outer call returns s after the recursion: 6. The second f(3) starts from 6 and adds 6 more: 12.

More C Programming questions

Exams that ask this topic