ProgrammingHardIBM · Deloitte pattern

What is printed? (recursive function returning a computed value through a chain of ternaries)

What is printed? (recursive function returning a computed value through a chain of ternaries)
int classify(int n) {
    return n == 0 ? 0 : (n % 2 == 0 ? 1 + classify(n - 2) : 1 + classify(n - 1));
}
int main(void) {
    printf("%d", classify(7));
}
  1. A. 7
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: C. 4

Each call peels off either 1 (odd n, step to n-1) or 2 (even n, step to n-2), adding exactly 1 to the result either way: 7->6->4->2->0 is 4 steps, so classify(7) = 4.

More C Programming questions

Exams that ask this topic