ProgrammingVery hardProduct company OA

What is printed? Assume no stack overflow for this depth.

What is printed? Assume no stack overflow for this depth.
int f(int n) {
    if (n == 0) return 0;
    if (n % 3 == 0) return 1 + f(n - 3);
    return f(n - 1);
}
int main(void) { printf("%d", f(10)); }
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 10

Correct answer: B. 3

f(10)->f(9) [not mult of 3 skip via n%3==0 check fails for 10, so f(9)]. f(9): 9%3==0, 1+f(6). f(6): 1+f(3). f(3): 1+f(0). f(0)=0. So f(3)=1, f(6)=2, f(9)=3, f(10)=f(9)=3 (10 isn't divisible by 3, it just passes through to f(9) with no +1).

More C Programming questions

Exams that ask this topic