- Asked 2/14
- 2075 Baisakh · 5 marks
- 2073 Bhadra · 8 marks
How recursion uses stack
Short answer
Each recursive call pushes an activation record with parameters and local variables onto the call stack, storing intermediate results. For factorial(3), frames for 3,2,1,0 are pushed; as the base case returns 1, each popped frame multiplies its n and returns the value, preserving partial computations.
How does a recursive algorithm use STACK to store intermediate results? Illustrate with an example and a suitable stack diagram.
A recursive function calls itself. Every call creates an activation record (stack frame) holding the parameters, local variables and the return address. These frames are pushed on the system call stack when a function is called and popped when it returns. Because the last call to start is the first to finish (LIFO), the stack stores the pending work and intermediate results of each call.
Example: factorial
int fact(int n) {
if (n == 0) return 1; /* base case */
return n * fact(n - 1); /* recursive case */
}
Calling fact(3):
Winding phase (calls, frames pushed)
step1 step2 step3 step4
| | | | | | |fact(0)|
| | | | |fact(1)| |fact(1)|
| | |fact(2)| |fact(2)| |fact(2)|
|fact(3)| |fact(3)| |fact(3)| |fact(3)|
+-------+ +-------+ +-------+ +-------+
Each frame holds its own n and waits for the result of the call above it. The call fact(0) meets the base case and returns 1.
Unwinding phase (returns, frames popped)
| Frame popped | Computation | Value returned |
|---|---|---|
| fact(0) | base case | 1 |
| fact(1) | 1 × 1 | 1 |
| fact(2) | 2 × 1 | 2 |
| fact(3) | 3 × 2 | 6 |
Result: fact(3) = 6.
Another example is Fibonacci, where the stack holds the pending fib(n-2) calls while fib(n-1) is being computed. Maximum stack depth equals the depth of recursion (n + 1 frames for factorial), so very deep recursion may cause stack overflow. Without the stack the function could not remember where to resume or the partial products, which is why recursion needs a stack (and why any recursive algorithm can be made iterative by using an explicit stack).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Recursion properties, Fibonacci, TOH algorithm · Data Structure and Algorithm, chapter 5
- Recursion; iterative vs recursive choice · Data Structure and Algorithm, chapter 5
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5
- TOH algorithm and recursion tree · Data Structure and Algorithm, chapter 5 · asked 2×
- Recursion, Fibonacci and TOH · Data Structure and Algorithm, chapter 5
- Normal vs recursive function · Data Structure and Algorithm, chapter 5
- Define influence line diagram and its uses · Theory of Structures I, chapter 5 · asked 5×
- Book store process model · Software Engineering, chapter 2
- Recursive/iterative query and DNS records · Computer Networks and Security, chapter 6
- Single stack stepper motor principle · Electrical Machine, chapter 7