- Get link
- X
- Other Apps
RECURSIVE IN PROGRAMMING
Recursion in programming is a technique where a function calls itself to solve a problem by repeatedly reducing it into smaller versions of the same problem.
Basic Structure
FUNCTION recursiveFunction(input):
IF stopping condition is TRUE:
RETURN result
ELSE:
RETURN recursiveFunction(smaller input)
The two essential parts are:
- Base Case → the condition that stops the recursion.
- Recursive Case → the function calls itself with a smaller/simpler input.
Example: Factorial
Mathematically:
5! = 5 × 4 × 3 × 2 × 1 = 120
Recursive Java example:
int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
Execution:
factorial(5)
↓
5 × factorial(4)
↓
4 × factorial(3)
↓
3 × factorial(2)
↓
2 × factorial(1)
↓
1
Then the results return upward:
1
↑
2 × 1 = 2
↑
3 × 2 = 6
↑
4 × 6 = 24
↑
5 × 24 = 120
Recursion vs. Looping
| Concept | Description |
|---|---|
| Looping / Iteration | Repeats a block using for, while, or do-while |
| Selection | Chooses between alternatives using if-else, switch |
| Recursion | A function repeatedly calls itself |
| Base Case | Stops recursion |
| Recursive Case | Continues recursion |
A simple way to remember it:
Iteration repeats a process. Recursion repeats a function by having the function call itself.
If the base case is missing or never reached, the program can continue calling itself until a stack overflow occurs.
Comments