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:
using System;
class Program
{
static void PrintHello(int n){
// Base Case
if (n == 0) return;
Console.WriteLine("Hello");
PrintHello(n - 1);
}
static void Main()
{
PrintHello(5);
}
}
Output
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.
Recursive Method
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:
- Base Condition: Stops recursion
- Recursive Case: Calls the method again
General Structure
returnType MethodName(parameters)
{
// Base Case
if (condition)
return value;
// Recursive Case
return MethodName(modified parameters);
}
How Recursion Works?
When a method calls itself:
- Each call is stored in stack memory (call stack)
- New calls are added (stack grows)
- When base condition is reached: calls start returning (stack shrinks)
The following example demonstrates both the descending phase (going deeper into recursion) and the ascending phase (returning back from recursion):
using System;
class Program
{
static void F(int n)
{
Console.WriteLine($"F({n})'s Stack Frame Pushed");
if (n > 1)
{
F(n - 1);
F(n - 1);
}
Console.WriteLine($"F({n})'s Stack Frame Removed");
}
static void Main()
{
F(3);
}
}
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:
Applications of Recursion
Recursion is commonly used in:
- Factorial and Fibonacci problems
- Searching & Sorting (Binary Search, QuickSort)
- Tree and Graph Traversal
- Backtracking problems
- Dynamic Programming
| 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 |