Write a Java program to calculate the factorial of a given number using recursion.
This program demonstrates the calculation of a factorial using recursion. The key element is the factorial method, which calls itself to compute the product of numbers from n down to 1. Here’s a detailed breakdown:
class Main {
public static void main(String[] args) {
int number = 5; // Input number for factorial calculation
int result = factorial(number); // Calculate factorial
// Properly format the output to display the result
System.out.println("Factorial of " + number + " is " + result);
}
// Recursive method to calculate factorial
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
}
Output:
Factorial of 5 is 120
How It Works
Main Method
number:
Set to 5 as an example input. You can replace it with any positive integer.
factorial(number):
Calls the recursive factorial method to compute the factorial of number.
Print Statement:
Outputs the formatted result as:
Factorial of 5 is 120
Recursive factorial Method
Base Case:
If n == 0 or n == 1, return 1. This prevents infinite recursion and handles the simplest cases.
Recursive Case:
For any n > 1, return n * factorial(n – 1). This breaks the problem into smaller pieces by repeatedly decreasing n until reaching the base case.
Example Execution for number = 5
Call Stack | Computation | Return Value |
factorial(5) | 5 * factorial(4) | Wait |
factorial(4) | 4 * factorial(3) | Wait |
factorial(3) | 3 * factorial(2) | Wait |
factorial(2) | 2 * factorial(1) | Wait |
factorial(1) (Base Case) | 1 | 1 |
Back to factorial(2) | 2 * 1 | 2 |
Back to factorial(3) | 3 * 2 | 6 |
Back to factorial(4) | 4 * 6 | 24 |
Back to factorial(5) | 5 * 24 | 120 |
Advantages of Recursive Approach
Intuitive Design:
Directly reflects the mathematical definition of factorial.
Compact Code:
Avoids explicit loops for clarity.
Considerations
Stack Overflow:
Recursion depth is limited by the system stack size. For very large inputs (e.g., n > 10,000), use an iterative approach instead.
Performance:
Recursion has overhead due to multiple function calls. Iterative methods are generally faster for large n.