ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
int f(int n) {
    int local = n;
    if (n == 0) return 0;
    local += f(n - 1);
    return local;
}
int main(void) {
    printf("%d", f(4));
}
  1. A. 4
  2. B. 14
  3. C. 24
  4. D. 10

Correct answer: D. 10

Each call has its OWN automatic local variable (unlike a static one), so there is no sharing between stack frames. local accumulates n + (n-1) + ... + 0 as the recursion unwinds: 4+3+2+1+0 = 10.

More C Programming questions

Exams that ask this topic