ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: B. 1 2 3 3 2 1

f prints n on the way in, recurses, then prints n again on the way out. f(4) returns immediately without printing (n>3). So: in: 1,2,3 (f(4) stops), then unwind prints 3,2,1 in reverse order of entry: 1 2 3 3 2 1.

More C Programming questions

Exams that ask this topic