Factorial Example using Recursion
What is Factorial?
The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Why use Recursion for Factorial?
- Factorial definition is naturally recursive:
n! = n × (n-1)! - Short and clean code compared to iterative loops.
Where to use Factorial (Real-world scenarios)
- Probability & statistics (e.g., permutations and combinations)
- Scientific calculations
- Combinatorics problems
Java Example – Recursive Factorial
public class FactorialRecursion {
// Recursive function to find factorial
static int factorial(int n) {
if (n == 0) { // Base case: factorial of 0 is 1
return 1;
}
return n * factorial(n - 1); // Recursive case
}
public static void main(String[] args) {
int num = 5;
System.out.println(num + "! = " + factorial(num));
}
}
5! = 120
How it works:
- You call factorial(5) in main().
- Since n is not 0, it does 5 × factorial(4).
- To find factorial(4), it does 4 × factorial(3).
- This keeps going until factorial(0) is called.
- factorial(0) returns 1 (base case).
- Now Java calculates: factorial(1) → 1 × 1 = 1 factorial(2) → 2 × 1 = 2 factorial(3) → 3 × 2 = 6 factorial(4) → 4 × 6 = 24 factorial(5) → 5 × 24 = 120