Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What does fun(3) print?

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

Correct answer: B. 1 2 1 3 1 2 1

fun(1) prints 1; fun(2) prints fun(1), 2, fun(1) = 1 2 1; fun(3) prints 1 2 1, 3, 1 2 1. In general 2ⁿ − 1 numbers are printed, the same pattern as Tower of Hanoi moves.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic