ProgrammingVery hardProduct company OA

What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value)

What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value)
int f(int n) {
    if (n <= 0) return 1;
    if (n % 2 == 0) return 2 * f(n - 1);
    return 1 + f(n - 1);
}
int main(void) {
    printf("%d", f(4));
}
  1. A. 9
  2. B. 16
  3. C. 8
  4. D. 10

Correct answer: D. 10

f(0)=1 (base case). f(1): odd -> 1+f(0) = 1+1 = 2. f(2): even -> 2*f(1) = 2*2 = 4. f(3): odd -> 1+f(2) = 1+4 = 5. f(4): even -> 2*f(3) = 2*5 = 10.

More C Programming questions

Exams that ask this topic