Question:
Write a recursive method named factorial
that takes an integer parameter n
and returns the factorial of that number. The factorial of a non-negative integer n
is denoted as n!
and is defined as the product of all positive integers less than or equal to n
.
For example, factorial(5)
should return 120, as 5! = 5 * 4 * 3 * 2 * 1 = 120.
Write the method factorial
to accomplish this using recursion.
Provide the Java code for the factorial
method, and also provide a step-by-step explanation of how the method works using an example call to factorial(5)
.
public class RecursiveMethods {
public static int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}
}
Explanation:
When the factorial
method is called with factorial(5)
, the following steps occur:
n
is equal to 0. Since it's not, it proceeds to the else block.factorial(4)
.factorial(4)
, it multiplies 4 with the return value of factorial(3)
.factorial(1)
is called, where the base case is triggered and it returns 1.factorial(5)
returns the result of 5 * 4 * 3 * 2 * 1, which is 120.This demonstrates how the recursive method factorial
works by breaking the original problem into smaller subproblems until reaching the base case, and then combining the results to obtain the final factorial value.