Sub topic 11
Write Methods That Call Themselves
A recursive method is a method that calls itself. It solves a problem by asking the same method to solve a smaller version of that problem.
Recursion is useful when a task can be broken into similar smaller tasks. For example, a method can work through folders inside folders. In this chapter, we will use a simpler example: multiplying a sequence of whole numbers.
A recursive method needs two parts:
- A base case is a case the method can answer without another call.
- A recursive case is a case where the method calls itself with a smaller problem.
The smaller problem must move toward the base case. Otherwise, the calls may never stop.
The factorial problem
The factorial of a nonnegative whole number is the product of that number and every positive whole number below it. For example:
- The factorial of 4 is
4 * 3 * 2 * 1, or 24. - The factorial of 3 is
3 * 2 * 1, or 6. - The factorial of 0 is defined as 1.
Notice that the factorial of 4 is also 4 times the factorial of 3. That gives us a way to make the problem smaller:
- If the number is 0, return 1. This is the base case.
- Otherwise, find the factorial of the number minus 1.
- Multiply that result by the original number.
The answer for 0 may seem unusual. It keeps the rule working for 1: the factorial of 1 is 1 * factorial(0), or 1.
Write and run the method
Save this program in a file named RecursionDemo.java:
class RecursionDemo {
static long factorial(int n) {
if (n < 0 || n > 20) {
throw new IllegalArgumentException("n must be between 0 and 20");
}
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(4));
System.out.println(factorial(0));
System.out.println(factorial(20));
}
}Compile and run it from the folder that contains the file:
javac RecursionDemo.java
java RecursionDemoThe output is:
24
1
2432902008176640000The method is named factorial. Its parameter, n, is the variable that receives the number for each call. The method returns a long, a Java type for whole numbers that can hold larger values than int.
The first if checks the input. If n is outside the range from 0 through 20, the method throws an IllegalArgumentException. An exception is a signal that something went wrong; this one tells the caller that the input is not accepted.
The second if is the base case. When n is 0, the method returns 1 without calling itself.
The last line is the recursive case:
return n * factorial(n - 1);For example, when n is 4, this line asks for factorial(3). It then multiplies the returned result by 4.
Follow the calls
Each call to factorial has its own n. Calling factorial(n - 1) does not change the n in the waiting call.
For factorial(4), the calls reach the base case like this:
The arrows show calls, not the order in which results return. The first four calls must wait for a smaller call to finish. The call with n equal to 0 can return immediately.
Once the base case returns 1, the waiting calls finish in reverse order:
| Call | What it returns |
|---|---|
| `factorial(0)` | `1` |
| `factorial(1)` | `1 * 1`, or `1` |
| `factorial(2)` | `2 * 1`, or `2` |
| `factorial(3)` | `3 * 2`, or `6` |
| `factorial(4)` | `4 * 6`, or `24` |
For instance, factorial(3) waits for factorial(2) to return 2. Then it multiplies that result by its own n, which is 3, and returns 6.
How Java remembers the calls
Java keeps track of active method calls in a call stack. You can think of it as a pile of records. Each record holds information a call needs while it runs or waits, including its parameter values.
When factorial(4) calls factorial(3), Java keeps the first call’s record and adds a record for the new call. This continues until factorial(0) returns.
When a call finishes, its record is removed. The result goes back to the call that was waiting for it. Returning through the waiting calls is often called unwinding the stack.
Make sure recursion stops
A base case alone is not enough. Every recursive call must also get closer to it.
In the example, each call uses n - 1. For an accepted positive input, repeated calls will eventually reach 0. The input check matters too: without it, a call such as factorial(-1) would move from -1 to -2, then -3, and so on. It would not reach the base case.
Here are common mistakes to look for:
- Missing base case: The method keeps calling itself because it has no stopping point.
- Wrong direction: A call such as
factorial(n + 1)moves away from 0 whennis positive. - Unchanged input: A call such as
factorial(n)repeats the same problem. - Work after the call is wrong: If the method adds instead of multiplying, it may stop but return the wrong result.
- Input outside the method’s rules: A stopping rule that works for nonnegative numbers may not work for negative numbers.
If too many calls are active at once, Java can stop the program with a StackOverflowError. This means the call stack ran out of space. A method can cause this error even if it would eventually reach a base case, because the stack has limited space.
Why the example has an upper limit
Factorial results grow quickly. Java’s long type has a maximum value, so it cannot hold every factorial. The factorial of 20 fits in a long, but the factorial of 21 does not.
For ordinary whole-number multiplication, Java does not automatically report that the result is too large. The result can be wrong. This is called overflow.
The example rejects values above 20 rather than returning an overflowed result. To see the check in action, change one call in main to factorial(21), then compile and run the program again. Java reports the exception instead of printing a factorial.
Choose recursion with care
Recursion can make a method easier to understand when each step naturally leads to a smaller version of the same task. Before writing it, ask:
- What is the smallest problem I can answer directly?
- How can I make the problem smaller?
- Will every accepted input reach the base case?
- What should I do with the result of the smaller call?
A loop is another way to repeat work. For a simple sequence such as factorial, a loop can avoid keeping many calls on the stack. Recursion may be a better fit when the problem itself has a nested shape, such as folders containing more folders.
Practice
Exercise
What does factorial(2) return, and which call reaches the base case?
Show answer
It returns 2. The calls are factorial(2), factorial(1), and factorial(0); factorial(0) reaches the base case and returns 1.
Exercise
What would happen if the recursive line called factorial(n) instead of factorial(n - 1), starting with n equal to 4?
Show answer
Every call would use 4, so none would reach the base case. Eventually, the program would run out of call stack space.
Exercise
Write a recursive method named sumTo that returns the sum from 1 through n. Assume n is between 0 and 100, and use 0 as the base case. What is sumTo(3)?
Show answer
One answer is static int sumTo(int n) { if (n == 0) return 0; return n + sumTo(n - 1); }. The result of sumTo(3) is 6.