ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
int f(int n) {
    if (n == 0) return 1;
    return n + f(n - 1);
}
int main(void) {
    printf("%d", f(100));
}
  1. A. 5050
  2. B. 100
  3. C. Stack overflow: undefined behaviour due to 100 levels of recursion
  4. D. 5051

Correct answer: D. 5051

f(100) computes 100+99+...+1+1 (the +1 comes from the base case f(0)=1, not 0), which is the sum 1..100 (5050) plus the extra 1 from the base case, giving 5051. 100 levels of recursion is well within any normal stack's capacity, so this is not a stack overflow concern.

More C Programming questions

Exams that ask this topic