Recursion with pre-decrement on both sides of a print: what is the output sequence? #include<stdio.h> void fun(int); typedef int (*pf)(int, int); int proc(pf, int, int); // (not used) int main() { int a = 3; fun(a); return 0; } void fun(int n) { if (n > 0) { fun(--n); printf("%d,", n); fun(--n); } }

Difficulty: Medium

Correct Answer: 0, 1, 2, 0,

Explanation:


Introduction / Context:
This recursion puzzle shows how pre-decrement (--n) changes the current frame’s local value before both the left and right recursive calls and between them, impacting the sequence of printed numbers.



Given Data / Assumptions:

  • Initial call: fun(3).
  • Inside fun: first call fun(--n), then print n, then call fun(--n) again.
  • Pre-decrement updates n before each use.


Concept / Approach:
Track the changing value of n carefully at each level. The first --n moves from 3 to 2 (then recurses). After returning, printing uses the decremented value from that frame. The second --n reduces once more before the right recursion.



Step-by-Step Solution:
Level n=3: first --n → 2; call fun(2).Level n=2: first --n → 1; call fun(1).Level n=1: first --n → 0; call fun(0) (returns immediately).Print at level n=1: prints 0, then second --n → -1, right call returns immediately.Back to level n=2: print 1, then second --n → 0, right call returns.Back to level n=3: print 2, then second --n → 1; call fun(1), which prints 0 similarly.Concatenate outputs: 0, 1, 2, 0,



Verification / Alternative check:
Manually instrumenting with trace messages or drawing a recursion tree confirms the exact print order.



Why Other Options Are Wrong:
Other sequences misplace the mid-print value or mis-handle the second pre-decrement.



Common Pitfalls:
Confusing pre-decrement with post-decrement; forgetting that n is mutated between the two recursive calls and before the print.



Final Answer:
0, 1, 2, 0,

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion