Recursion is a programming technique in which a function calls itself to solve a problem. A recursive function repeatedly calls itself until a base condition is met. Without a base condition, the recursion continues indefinitely and may cause a stack overflow.
Syntax
return_type function_name(parameters)
{
if (base_condition)
return value;
else
return function_name(modified_parameters);
}
Components of Recursion
- Base Case – Stops the recursive calls.
- Recursive Case – The function calls itself with modified arguments.
Example 1: Factorial Using Recursion
The factorial of a number is:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 0! = 1
Program
#include <stdio.h>
int factorial(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main()
{
int num = 5;
printf("Factorial of %d = %d", num, factorial(num));
return 0;
}
Output
Factorial of 5 = 120
Working
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 120
Example 2: Fibonacci Series Using Recursion
Program
#include <stdio.h>
int sum(int n)
{
if (n == 1)
return 1;
else
return n + sum(n - 1);
}
int main()
{
int n = 5;
printf("Sum = %d", sum(n));
return 0;
}
Output
Fibonacci Series:0 1 1 2 3 5 8 13 21 34
Advantages of Recursion
- Makes code shorter and easier to understand.
- Suitable for problems that can be divided into smaller subproblems.
- Useful for tree and graph traversal, factorial, Fibonacci, and divide-and-conquer algorithms.
Disadvantages of Recursion
- Uses more memory due to function call stack.
- Can be slower than iterative solutions.
- Incorrect or missing base case can lead to infinite recursion and stack overflow.
Difference Between Recursion and Iteration
| Recursion | Iteration |
|---|---|
| Function calls itself | Uses loops (for, while) |
| Requires a base case | Requires a loop condition |
| Uses more memory (call stack) | Uses less memory |
| Code is often shorter | Code may be longer but usually faster |
Key Point
A recursive function must always have a base case to terminate the recursion. Without it, the function will keep calling itself until the program crashes due to a stack overflow.
Category: MCA
