Recursion: Tracing Recursive Calls
Determining the result of calling recursive methods: base cases and recursive calls, separate local variables for every call, output before and after the recursive call, parameters as a record of progress, missing base cases, and the link between recursion and loops.
A recursive method is a method that calls itself. It contains at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition. Each recursive call has its own set of local variables, including the parameters, and parameter values capture the progress of a recursive process the way loop control variables capture the progress of a loop. Any recursive solution can be replicated with an iterative approach, and vice versa. The skill here is tracing: determining what a call to a recursive method returns or prints.
1A Method That Calls Itself
A recursive method solves a problem by calling itself on a smaller version of the same problem. To add the numbers from 1 to n, sumTo(n) adds n to the result of sumTo(n - 1). That call does the same with n - 2, and so on, until a problem is small enough to answer directly.
That directly answered problem is the base case: a condition under which the method returns without calling itself, which halts the recursion. Every recursive method has at least one base case and at least one recursive call. Recursion is another form of repetition: instead of a loop body running again, the method body runs again in a new call.
To determine what a call returns, first find the base case and what it returns. Then follow the recursive calls from the original argument down to the base case, noting each parameter value. Finally, work back up, combining each call's own work with the value returned to it. The figure below labels the two required parts in a short method.
| Part | Role | In sumTo |
|---|---|---|
| Base case | Halts the recursion and returns without calling again | if (n == 0) return 0; |
| Recursive call | Calls the same method on a smaller problem | sumTo(n - 1) |
| Parameters | Capture the progress of the process, like a loop variable | n decreases by 1 each call |
| Local variables | Separate for every call | Each call has its own n |
Adding on the Way Back
Predict the output.
public static int sumTo(int n)
{
if (n == 0)
{
return 0;
}
return n + sumTo(n - 1);
}
10
0
- 1Calls go down: sumTo(4) needs sumTo(3), which needs sumTo(2), then sumTo(1), then sumTo(0).
- 2Base case: sumTo(0) returns 0 without calling again.
- 3Returns come back up: 1 + 0 = 1, then 2 + 1 = 3, 3 + 3 = 6, and 4 + 6 = 10.
- 4sumTo(0) is the base case immediately: 0.
2Every Call Has Its Own Variables
Each recursive call has its own set of local variables, including the parameters. When sumTo(4) calls sumTo(3), the new call gets a fresh n equal to 3; the first call's n is still 4, waiting. While the deeper calls run, every earlier call is paused at the point of its recursive call, remembering its own values.
Tracing recursion means keeping these calls apart. A reliable method is to write each call on its own line, with its parameter values and what it is waiting for, as in the trace table below. When the base case returns, work back up the table, finishing each paused call in turn, from the most recent to the first.
n; the calls stop at the base case and the results return in reverse order.| Call | n | Waits for | Returns |
|---|---|---|---|
| sumTo(4) | 4 | sumTo(3) | 4 + 6 = 10 |
| sumTo(3) | 3 | sumTo(2) | 3 + 3 = 6 |
| sumTo(2) | 2 | sumTo(1) | 2 + 1 = 3 |
| sumTo(1) | 1 | sumTo(0) | 1 + 0 = 1 |
| sumTo(0) | 0 | nothing (base case) | 0 |
The n in sumTo(1) is a different variable from the n in sumTo(4). When a deeper call returns, the earlier call continues with its own value of n, unchanged.
3Work Before and After the Recursive Call
Where a statement sits relative to the recursive call decides when it runs. Statements before the call run as the calls are made, going down: a method that prints n and then calls itself with n - 1 prints 3, 2, 1. Statements after the call cannot run until the deeper calls have all returned, so they run on the way back up, in reverse order: moving the print below the call prints 1, 2, 3.
A method with statements on both sides produces a mirror pattern: the "before" statements in order, then the "after" statements in reverse. Tracing such a method is easiest with two passes: list the calls going down, then list them again coming back up.
Counting Down
Predict the output.
public static void countDown(int n)
{
if (n > 0)
{
System.out.println(n);
countDown(n - 1);
}
else
{
System.out.println("done");
}
}
3
2
1
done
- 1Each call prints first, then makes the next call, so the values appear in the order the calls are made: 3, 2, 1.
- 2The base case (n is 0) prints "done" and makes no further call.
Counting Up
The print statement now comes after the recursive call. Predict the output.
public static void countUp(int n)
{
if (n > 0)
{
countUp(n - 1);
System.out.println(n);
}
}
1
2
3
- 1countUp(3) cannot print yet: it must wait for countUp(2), which waits for countUp(1), which waits for countUp(0).
- 2countUp(0) does nothing and returns.
- 3The waiting calls finish in reverse order: countUp(1) prints 1, then countUp(2) prints 2, then countUp(3) prints 3.
A Mirror Pattern
Predict the output.
public static void mirror(int n)
{
if (n > 0)
{
System.out.println("in " + n);
mirror(n - 1);
System.out.println("out " + n);
}
}
in 2
in 1
out 1
out 2
- 1Going down: mirror(2) prints "in 2", then mirror(1) prints "in 1", then mirror(0) does nothing.
- 2Coming back: mirror(1) resumes and prints "out 1"; then mirror(2) resumes and prints "out 2".
Output placed after the recursive call appears in the reverse of the call order, because the most recent call finishes first. In countUp(3), the 3 is printed last, not first.
4Parameters Capture the Progress
Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop. In digits(n), each call divides n by 10, so the parameter loses one digit per call: 40719, 4071, 407, 40, 4. Reading the sequence of parameter values tells how many calls are made and when the base case is reached.
Some methods make more than one recursive call. Then the calls form a tree instead of a single chain: each call can branch into two more. Counting calls means counting every node of the tree, and the same smaller call may appear in several places.
Counting Digits
Predict the output (Figure 4).
public static int digits(int n)
{
if (n < 10)
{
return 1;
}
return 1 + digits(n / 10);
}
5
1
- 1Each call divides by 10, dropping the last digit: 40719, 4071, 407, 40, 4.
- 24 is less than 10: the base case returns 1.
- 3Each earlier call adds 1 on the way back: 5. A one-digit number is the base case at once: 1.
Counting the Calls
A method can call itself more than once. A static variable counts every call. Predict the output.
public static int calls = 0;
public static int ways(int n)
{
calls++;
if (n <= 1)
{
return 1;
}
return ways(n - 1) + ways(n - 2);
}
5 9
- 1ways(4) = ways(3) + ways(2); ways(3) = ways(2) + ways(1); ways(2) = ways(1) + ways(0).
- 2Base cases ways(1) and ways(0) each return 1, so ways(2) = 2, ways(3) = 3, and ways(4) = 5.
- 3Calls: ways(4) once, ways(3) once, ways(2) twice, ways(1) three times, ways(0) twice: 9.
When a method calls itself twice, the second call runs after the first returns, and it makes its own calls too. Draw the whole tree of calls before counting calls or adding results.
5When Recursion Never Stops
If a base case is missing, or the recursive calls never reach it, the method keeps calling itself. Every paused call takes memory, and eventually Java runs out and throws a StackOverflowError. This is the recursive version of an infinite loop.
A base case being present is not enough; it must be reachable. A method whose base case is n == 0 but whose parameter decreases by 2 reaches 0 from even numbers and skips past it from odd numbers. When tracing, check whether the parameter values actually arrive at the base case for the given argument.
Skipping Over Zero
What happens?
public static int halves(int n)
{
if (n == 0)
{
return 0;
}
return 1 + halves(n - 2);
}
- 1halves(4) calls with 2, then 0: the base case is reached, and the result is 2.
- 2halves(5) calls with 3, 1, −1, −3, …: n is never exactly 0, so the calls never stop.
- 3Each call uses memory until Java runs out and throws a
StackOverflowError.
StackOverflowError. A base case must be reachable from every starting value the method is called with.A base case of n == 0 is never reached if n starts negative or jumps over 0. Check the starting argument and the change made by each call against the base case condition.
6Recursion and Iteration
Any recursive solution can be replicated through the use of an iterative approach, and vice versa. A recursive method that decreases its parameter by 1 until a base case corresponds to a loop whose control variable counts down until the loop condition fails. The base case plays the role of the loop's stopping condition, and the recursive call plays the role of the next pass.
Seeing the correspondence makes recursive code easier to trace: identify what the parameter does on each call, what the base case returns, and how each call combines its own work with the result of the call it makes. Then the result can be computed just as for the equivalent loop.
| Recursion | Iteration | |
|---|---|---|
| Repeats by | The method calling itself | A loop body running again |
| Progress kept in | Parameter values of each call | The loop control variable |
| Stops when | A base case is reached | The loop condition is false |
| If it never stops | StackOverflowError | The program runs forever |
The Same Result Without Recursion
A recursive method and a loop compute the same power. Predict the output.
public static int powerRec(int base, int exp)
{
if (exp == 0)
{
return 1;
}
return base * powerRec(base, exp - 1);
}
public static int powerLoop(int base, int exp)
{
int result = 1;
for (int k = exp; k > 0; k--)
{
result *= base;
}
return result;
}
32 32
1 1
- 1Recursive version: 2 × 2 × 2 × 2 × 2 × 1, one factor per call, ending at the base case
exp == 0. - 2Loop version:
kcounts down fromexplike the parameter does, multiplying once per pass. - 3Zero exponent: both return 1 immediately.
Four Habits for Tracing Recursion
1. Find the Base Case
And check that the calls reach it.
2. One Line per Call
With its own parameter values.
3. Down, Then Up
Before-call work going down; after-call work coming back.
4. Trees for Two Calls
Count every node.
A recursive method is a method that calls itself. Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition. Each recursive call has its own set of local variables, including the parameters. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop. Any recursive solution can be replicated through the use of an iterative approach and vice versa.