ProgrammingHardAccenture · Cognizant pattern

What does f(3) print?

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

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

f(1) prints 1. f(2) = f(1), 2, f(1) = 1 2 1. f(3) = f(2), 3, f(2) = 1 2 1 3 1 2 1. This is the in-order pattern of the Tower of Hanoi recursion: 2³ - 1 = 7 numbers.

More C Programming questions

Exams that ask this topic