ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int c = 0;
int f(int n) {
    c++;
    return n > 0 && (f(n - 1) || f(n - 2));
}
int main(void) {
    int r = f(4);
    printf("%d %d", r, c);
}
  1. A. 0 9
  2. B. 1 15
  3. C. 1 9
  4. D. 0 15

Correct answer: D. 0 15

Any n ≤ 0 returns 0, so by induction every call returns 0, and the || never short-circuits: both f(n − 1) and f(n − 2) always run. Calls: C(n) = 1 for n ≤ 0, else 1 + C(n − 1) + C(n − 2): C(1) = 3, C(2) = 5, C(3) = 9, C(4) = 15.

More C Programming questions

Exams that ask this topic