ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: D. 1 2 3 1

f(3) = f(2), print 3, f(1). f(2) = f(1), print 2, f(0); f(1) = f(0), print 1, f(−1). So: (1) 2 3 then f(1) prints 1 → 1 2 3 1. This is an in-order walk of the recursion tree.

More C Programming questions

Exams that ask this topic