ProgrammingHardIBM · Deloitte pattern

What is printed?

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

Correct answer: D. 3 2 1 1 2 3

Each call prints n BEFORE recursing (going down: 3, 2, 1) and prints n again AFTER the recursive call returns (unwinding back up: 1, 2, 3, in reverse order since the deepest call returns first). Output: 3 2 1 1 2 3.

More C Programming questions

Exams that ask this topic