Sub topic 11
Write Methods That Call Themselves
A method can call itself to solve a problem in smaller steps. This technique is called recursion. It can be useful when a problem has a simple answer for a small input and a rule for reducing larger inputs.
A recursive method needs two parts:
- A base case is an input with a known answer. It stops the method from making another recursive call.
- A recursive case reduces the problem and calls the method again.
Calculate a factorial
A factorial is the result of multiplying a whole number by every positive whole number below it. For example, the factorial of 4 is 4 × 3 × 2 × 1, or 24. By definition, the factorial of 0 is 1.
We can use that definition to write a recursive method:
- If the number is 0, return 1. This is the base case.
- Otherwise, multiply the number by the factorial of the number one smaller. This is the recursive case.
Save this program as RecursionDemo.java:
class RecursionDemo {
static int factorial(int n) {
if (n < 0 || n > 12) {
throw new IllegalArgumentException("n must be from 0 to 12");
}
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(4));
}
}Compile and run it from the folder containing the file:
javac RecursionDemo.java
java RecursionDemoThe program prints 24.
The first condition checks the input. If it is outside 0 through 12, the method throws an exception, a signal that something went wrong. The upper limit matters because larger factorials do not fit in an int, which can hold only a limited range of whole numbers.
Follow the calls and returns
The call factorial(4) is not answered at once. It needs the answer to factorial(3), which needs the answer to factorial(2), and so on:
- factorial(4) waits for 4 × factorial(3).
- factorial(3) waits for 3 × factorial(2).
- factorial(2) waits for 2 × factorial(1).
- factorial(1) waits for 1 × factorial(0).
- factorial(0) reaches the base case and returns 1.
The waiting calls can now finish, starting with the most recent one:
| Call | Calculation | Result returned |
|---|---|---|
| factorial(0) | Base case | 1 |
| factorial(1) | 1 × 1 | 1 |
| factorial(2) | 2 × 1 | 2 |
| factorial(3) | 3 × 2 | 6 |
| factorial(4) | 4 × 6 | 24 |
Each call has its own value of the parameter n. When factorial(4) calls factorial(3), the first call still has n equal to 4. It waits until the second call returns a result.
Make sure recursion stops
Check that every recursive call moves toward the base case. Here, subtracting 1 moves each valid positive input closer to 0. The input check rejects negative numbers, which would otherwise move farther from 0.
Java keeps track of waiting calls in memory called the call stack. Too many waiting calls can cause a stack overflow, which stops the program. For a long sequence of steps, a loop may be a simpler choice because it does not need a new method call for each step.
Practice
Exercise
What calls happen when the program calls factorial(2), and what result does it return?
Show answer
factorial(2) calls factorial(1), which calls factorial(0). The base case returns 1, then factorial(1) returns 1 and factorial(2) returns 2.
Exercise
What happens if the program calls factorial(13)?
Show answer
The input check throws an exception before the method makes a recursive call. The result would be too large for an int.