Consider the following two functions: void fun1(int n) { if (n == 0) return; printf("%d", n); fun2(n - 2); printf("%d", n); } void fun2(int n) { if (n == 0) return; printf("%d", n); fun1(n - 1); printf("%d", n); } The output printed when fun1(5) is called is: A. 5 3 2 2 3 5 B. 5 3 1 1 3 5 C. 5 3 2 3 5 D. 5 3 1 3 5

GATE 2017 · Programming and Data Structures · Recursion · medium

Answer: The output printed when fun1(5) is called is 5 3 2 2 3 5 — option A.

  1. Forward trace — prints on the way down: fun1(5): print 5, call fun2(3) fun2(3): print 3, call fun1(2) fun1(2): print 2, call fun2(0) fun2(0): n==0, return immediately (no print) Forward output: 5 3 2
  2. Backward trace — prints on the way back up: fun1(2) resumes after fun2(0) returns: print 2 fun2(3) resumes after fun1(2) returns: print 3 fun1(5) resumes after fun2(3) returns: print 5 Backward output: 2 3 5
  3. Full output: Complete output = forward + backward = 5 3 2 + 2 3 5 = 5 3 2 2 3 5