ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
#include <stdio.h>
void f(int n) {
    if (n <= 0) { printf("B "); return; }
    if (n % 2 == 0) printf("E%d ", n);
    else printf("O%d ", n);
    f(n - 2);
}
int main(void) {
    f(5);
}
  1. A. O5 O3 O1 B
  2. B. O5 O3 O1
  3. C. E5 E3 E1 B
  4. D. O5 O3 O1 O-1 B

Correct answer: A. O5 O3 O1 B

n descends 5, 3, 1, -1 in steps of 2. 5, 3 and 1 are all odd, each printing O<n>. When n becomes -1, the base case n<=0 fires immediately, printing B without reaching the odd/even check, giving O5 O3 O1 B.

More C Programming questions

Exams that ask this topic