Sub topic 15
Tracing Recursive Calls and Predicting Output
Assume you know C functions, if statements, loops, and basic stack behavior. This chapter shows how to trace recursive calls and determine their output without running the program.
Read a recursive function in two phases
A recursive function has:
- A base case, which stops recursion.
- A recursive case, which calls the same function with a smaller or simpler input.
The position of printf matters. A statement before the recursive call runs while the calls go deeper. A statement after the recursive call runs while the calls return.
#include <stdio.h>
void show(int n) {
if (n == 0) {
return;
}
printf("%d ", n);
show(n - 1);
printf("%d ", n);
}
int main(void) {
show(3);
printf("\n");
return 0;
}Trace the calls:
| Event | Action | Output so far |
|---|---|---|
| `show(3)` enters | print `3` | `3` |
| `show(2)` enters | print `2` | `3 2` |
| `show(1)` enters | print `1` | `3 2 1` |
| `show(0)` enters | return | `3 2 1` |
| `show(1)` resumes | print `1` | `3 2 1 1` |
| `show(2)` resumes | print `2` | `3 2 1 1 2` |
| `show(3)` resumes | print `3` | `3 2 1 1 2 3` |
The output is:
3 2 1 1 2 3Each invocation has its own n. When show(1) returns, execution continues at the statement after its recursive call. The caller's value, such as n == 2, remains unchanged in its own stack frame.
Use the call stack
For every recursive question, write each call as a separate frame. Record what happens before the recursive call, then continue from the saved point after the call returns.
Tree recursion
A function can make more than one recursive call.
int f(int n) {
if (n <= 1) {
return 1;
}
return f(n - 1) + f(n - 2);
}For f(4), expand both calls until reaching the base case. The same subproblems appear repeatedly, such as f(2). This repetition affects time complexity even when the final numeric result is easy to calculate.
When tracing C code, also check whether an expression changes and reads the same object without a guaranteed evaluation order. Such code can have undefined behavior, so it has no single output required by C.
Exercise
What does print(3) output if it prints n before calling print(n - 1), and prints * after the call, with a base case of n == 0?
Show answer
3 2 1 * * *