ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: A. 3 2 1 1 2 3

Each call prints n before recursing deeper and again after the deeper call returns. Descending prints 3 2 1; the base case n==0 prints nothing; unwinding then reprints 1 2 3 in reverse.

More C Programming questions

Exams that ask this topic