ProgrammingHardIBM · Deloitte pattern

What is printed? (recursion with an early return skipping the rest of the function)

What is printed? (recursion with an early return skipping the rest of the function)
int f(int n) {
    if (n < 0) return -1;
    if (n == 0) return 0;
    int r = f(n - 1);
    if (r == -1) return -1;
    return r + n;
}
int main(void) {
    printf("%d", f(4));
}
  1. A. -1
  2. B. 4
  3. C. 10
  4. D. 0

Correct answer: C. 10

No n ever goes negative here (f is only ever called with n, n-1, ... down to 0), so the -1 short-circuit path is never taken; this just computes 4+3+2+1+0 = 10.

More C Programming questions

Exams that ask this topic