ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
#include <stdio.h>
int odds = 0;
void f(int n) {
    if (n == 0) return;
    if (!(n % 2)) { f(n - 1); return; }
    odds++;
    f(n - 1);
}
int main(void) {
    f(6);
    printf("%d", odds);
}
  1. A. 2
  2. B. 6
  3. C. 1
  4. D. 3

Correct answer: D. 3

!(n % 2) is true exactly when n is even, in which case the function just recurses without counting. odds is only incremented for the odd values visited: 5, 3 and 1, so odds ends at 3.

More C Programming questions

Exams that ask this topic