![]() |
VOOZH | about |
Recursion is a programming technique where a method calls itself repeatedly until a specific base condition is met. A method that performs this behavior is called a recursive method, and each self-call is known as a recursive call. Example:
Hello Hello Hello Hello Hello
The method PrintHello(n) prints "Hello" and calls itself with n-1 until n == 0. When the base condition is reached, recursion stops.
A method that calls itself is known as a recursive method. It breaks a problem into smaller subproblems of the same type.
A recursive method must have:
When a method calls itself:
The following example demonstrates both the descending phase (going deeper into recursion) and the ascending phase (returning back from recursion):
Output:
F(3)'s Stack Frame Pushed
F(2)'s Stack Frame Pushed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(2)'s Stack Frame Removed
F(2)'s Stack Frame Pushed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(2)'s Stack Frame Removed
F(3)'s Stack Frame Removed
Below is the illustration of function call stack of the above code:
Recursion is commonly used in:
| Advantages of Recursion | Disadvantages of Recursion |
|---|---|
| Code is short and clean | Higher memory usage |
| Easy to solve complex problems | Can be slower than iteration |
| Natural fit for tree/graph problems | Risk of stack overflow |
| Improves code readability | Harder to debug |