AP Computer Science A · Study guide

Recursive Method Calls

AP® Computer Science A · Data Collections

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.

Big Picture

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.

Figure 1. A recursive method contains at least one base case, which halts the recursion, and at least one recursive call.
PartRoleIn sumTo
Base caseHalts the recursion and returns without calling againif (n == 0) return 0;
Recursive callCalls the same method on a smaller problemsumTo(n - 1)
ParametersCapture the progress of the process, like a loop variablen decreases by 1 each call
Local variablesSeparate for every callEach call has its own n
Worked Example 1 Return values

Adding on the Way Back

Predict the output.

Code
public static int sumTo(int n)
{
    if (n == 0)
    {
        return 0;
    }
    return n + sumTo(n - 1);
}
Output
10
0
  1. 1Calls go down: sumTo(4) needs sumTo(3), which needs sumTo(2), then sumTo(1), then sumTo(0).
  2. 2Base case: sumTo(0) returns 0 without calling again.
  3. 3Returns come back up: 1 + 0 = 1, then 2 + 1 = 3, 3 + 3 = 6, and 4 + 6 = 10.
  4. 4sumTo(0) is the base case immediately: 0.
Result: The output is 10 and 0. A recursive method's result is built as each call returns its value to the call that made it.

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.

Figure 2. Each recursive call has its own set of local variables, including its parameter n; the calls stop at the base case and the results return in reverse order.
CallnWaits forReturns
sumTo(4)4sumTo(3)4 + 6 = 10
sumTo(3)3sumTo(2)3 + 3 = 6
sumTo(2)2sumTo(1)2 + 1 = 3
sumTo(1)1sumTo(0)1 + 0 = 1
sumTo(0)0nothing (base case)0
Common Mistake 1 · Treating All Calls as Sharing One Variable

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.

Figure 3. Statements before the recursive call run as the calls go down; statements after it run as the calls return, in reverse order.
Worked Example 2 Printing before the call

Counting Down

Predict the output.

Code
public static void countDown(int n)
{
    if (n > 0)
    {
        System.out.println(n);
        countDown(n - 1);
    }
    else
    {
        System.out.println("done");
    }
}
Output
3
2
1
done
  1. 1Each call prints first, then makes the next call, so the values appear in the order the calls are made: 3, 2, 1.
  2. 2The base case (n is 0) prints "done" and makes no further call.
Result: The output is 3, 2, 1, done. Statements before a recursive call run in the order the calls are made.
Worked Example 3 Printing after the call

Counting Up

The print statement now comes after the recursive call. Predict the output.

Code
public static void countUp(int n)
{
    if (n > 0)
    {
        countUp(n - 1);
        System.out.println(n);
    }
}
Output
1
2
3
  1. 1countUp(3) cannot print yet: it must wait for countUp(2), which waits for countUp(1), which waits for countUp(0).
  2. 2countUp(0) does nothing and returns.
  3. 3The waiting calls finish in reverse order: countUp(1) prints 1, then countUp(2) prints 2, then countUp(3) prints 3.
Result: The output is 1, 2, 3. Statements after a recursive call run as the calls return, in the reverse of the order in which they were made (Figure 3).
Worked Example 4 Before and after

A Mirror Pattern

Predict the output.

Code
public static void mirror(int n)
{
    if (n > 0)
    {
        System.out.println("in " + n);
        mirror(n - 1);
        System.out.println("out " + n);
    }
}
Output
in 2
in 1
out 1
out 2
  1. 1Going down: mirror(2) prints "in 2", then mirror(1) prints "in 1", then mirror(0) does nothing.
  2. 2Coming back: mirror(1) resumes and prints "out 1"; then mirror(2) resumes and prints "out 2".
Result: The output is in 2, in 1, out 1, out 2. Each call resumes exactly where it left off after its recursive call returns.
Common Mistake 2 · Printing After the Call in Forward Order

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.

Figure 4. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
Worked Example 5 Parameters as progress

Counting Digits

Predict the output (Figure 4).

Code
public static int digits(int n)
{
    if (n < 10)
    {
        return 1;
    }
    return 1 + digits(n / 10);
}
Output
5
1
  1. 1Each call divides by 10, dropping the last digit: 40719, 4071, 407, 40, 4.
  2. 24 is less than 10: the base case returns 1.
  3. 3Each earlier call adds 1 on the way back: 5. A one-digit number is the base case at once: 1.
Result: The output is 5 and 1. The parameter's value in each call shows how far the process has progressed, just as a loop variable does.
Worked Example 6 Two recursive calls

Counting the Calls

A method can call itself more than once. A static variable counts every call. Predict the output.

Code
public static int calls = 0;

public static int ways(int n)
{
    calls++;
    if (n <= 1)
    {
        return 1;
    }
    return ways(n - 1) + ways(n - 2);
}
Output
5 9
  1. 1ways(4) = ways(3) + ways(2); ways(3) = ways(2) + ways(1); ways(2) = ways(1) + ways(0).
  2. 2Base cases ways(1) and ways(0) each return 1, so ways(2) = 2, ways(3) = 3, and ways(4) = 5.
  3. 3Calls: ways(4) once, ways(3) once, ways(2) twice, ways(1) three times, ways(0) twice: 9.
Result: The output is 5 9. When a method makes two recursive calls, draw the calls as a tree and count every node.
Common Mistake 3 · Counting Only One Branch

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.

Worked Example 7 Unreachable base case

Skipping Over Zero

What happens?

Code
public static int halves(int n)
{
    if (n == 0)
    {
        return 0;
    }
    return 1 + halves(n - 2);
}
  1. 1halves(4) calls with 2, then 0: the base case is reached, and the result is 2.
  2. 2halves(5) calls with 3, 1, −1, −3, …: n is never exactly 0, so the calls never stop.
  3. 3Each call uses memory until Java runs out and throws a StackOverflowError.
Result: The program prints 2 and then stops with a StackOverflowError. A base case must be reachable from every starting value the method is called with.
Common Mistake 4 · A Base Case the Calls Skip Past

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.

RecursionIteration
Repeats byThe method calling itselfA loop body running again
Progress kept inParameter values of each callThe loop control variable
Stops whenA base case is reachedThe loop condition is false
If it never stopsStackOverflowErrorThe program runs forever
Worked Example 8 Equivalent loop

The Same Result Without Recursion

A recursive method and a loop compute the same power. Predict the output.

Code
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;
}
Output
32 32
1 1
  1. 1Recursive version: 2 × 2 × 2 × 2 × 2 × 1, one factor per call, ending at the base case exp == 0.
  2. 2Loop version: k counts down from exp like the parameter does, multiplying once per pass.
  3. 3Zero exponent: both return 1 immediately.
Result: The output is 32 32 and 1 1. Any recursive solution can be replicated through an iterative approach, and vice versa.

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.

Core Synthesis

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.