Recursion
Recursion is a technique where a method calls itself to solve a problem. It's often used to break down complex problems into simpler versions of themselves.
How It Works
Every recursive method needs two parts:
- Base Case: The condition to stop calling itself (otherwise, it loops forever and crashes).
- Recursive Case: The part where the method calls itself with a modified parameter (moving towards the base case).
int factorial(int n) {
if (n == 1) {
return 1; // Base Case: Stop!
} else {
return n * factorial(n - 1); // Recursive Step
}
}
Example: Mathematical Factorial
The factorial of 5 (written as 5!) is 5 * 4 * 3 * 2 * 1.
factorial(5)returns5 * factorial(4)factorial(4)returns4 * factorial(3)- ...and so on, until
factorial(1)returns 1.
Output
Click Run to execute your code
Stack Overflow Error
If you forget the Base Case, the method keeps calling itself infinitely until the
computer runs out of memory. In Java, this throws a
StackOverflowError.
// BAD CODE (Crashes)
int badMethod(int n) {
return n * badMethod(n - 1); // No stopping condition!
}
Summary
- Recursion is when a function calls itself.
- Always define a Base Case to stop the recursion.
- Useful for traversing trees, directories, or solving mathematical series.
Enjoying these tutorials?