ProgrammingHardIBM · Deloitte pattern

What is printed? (recursion where the base case is reached via an off-by-one condition)

What is printed? (recursion where the base case is reached via an off-by-one condition)
int f(int n) {
    if (n < 1) return 0;
    return n + f(n - 2);
}
int main(void) {
    printf("%d", f(6));
}
  1. A. 21
  2. B. 12
  3. C. 6
  4. D. 9

Correct answer: B. 12

f(6)=6+f(4)=6+4+f(2)=6+4+2+f(0, which is <1 so returns 0)=6+4+2+0=12. Note f only ever sees even n here (6,4,2,0), so the sum is 6+4+2=12.

More C Programming questions

Exams that ask this topic