Recursion in Java is a technique where a method calls itself to solve a problem. It can be a powerful tool for solving problems that can be broken down into smaller, similar problems. Here's a simple explanation for beginners:
Key Concepts:
- Base Case: This is the condition that stops the recursion. Without a base case, the method would call itself indefinitely, causing a stack overflow error.
- Recursive Case: This is where the method calls itself with a different argument, moving closer to the base case with each call.
Example:
Let's look at a classic example: calculating the factorial of a number.
Factorial Definition:
The factorial of a number (denoted as ) is the product of all positive integers up to .
For example
Recursive Definition:
- The factorial of 0 is 1. This is the base case.
- The factorial of is . This is the recursive case.
Java Code:
public class Factorial {
// Method to calculate factorial using recursion
public static int factorial(int n) {
// Base case: if n is 0, return 1
if (n == 0) {
return 1;
}
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is " + result);
}
}
How It Works:
- Initial Call:
factorial(5)
- First Recursive Call:
5 * factorial(4)
- Second Recursive Call:
5 * (4 * factorial(3))
- Third Recursive Call:
5 * (4 * (3 * factorial(2)))
- Fourth Recursive Call:
5 * (4 * (3 * (2 * factorial(1))))
- Fifth Recursive Call:
5 * (4 * (3 * (2 * (1 * factorial(0)))))
- Base Case Reached:
factorial(0)
returns 1
The final result is 120, which is the factorial of 5.
Comments
Post a Comment