
Recursion in C
Recursion is a technique in C where a function calls itself to solve smaller instances of a problem.
"Recursion is like a loop with memory - it keeps track of previous function calls until it reaches a base case."
What is Recursion?
Recursion is a method where a function calls itself in order to break down a problem into smaller subproblems. Every recursive function must have a base case to prevent infinite recursion.
Types of Recursion
Type | Description | Example |
---|---|---|
Direct Recursion | A function calls itself directly. | void func() { func(); } |
Indirect Recursion | Two or more functions call each other. | void funcA() { funcB(); } void funcB() { funcA(); } |
Tail Recursion | The recursive call is the last operation in the function. | return func(n-1); |
Head Recursion | The recursive call is made at the beginning of the function. | func(n-1); return; |
Examples of Recursion
1. Factorial of a Number (Using Recursion)
#include <stdio.h>
long factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %ld\n", num, factorial(num));
return 0;
}
2. Fibonacci Sequence (Using Recursion)
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) return n; // Base case
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 5;
printf("Fibonacci sequence value at position %d is %d\n", n, fibonacci(n));
return 0;
}
3. Printing Numbers in Reverse Order (Using Recursion)
#include <stdio.h>
void printReverse(int n) {
if (n == 0) return; // Base case
printf("%d ", n);
printReverse(n - 1);
}
int main() {
printReverse(5);
return 0;
}
Advantages of Recursion
- Reduces the complexity of code for problems like tree traversal and Fibonacci series.
- Some problems are naturally recursive (e.g., Tower of Hanoi, factorial, Fibonacci).
- Makes code easier to read and maintain.
Disadvantages of Recursion
- Uses more memory due to function call stack.
- Can lead to stack overflow if the base case is not defined.
- May be slower compared to iterative solutions due to overhead of function calls.
Best Practices for Using Recursion
- Always define a **base case** to stop recursion.
- For performance-sensitive programs, use **iteration instead of recursion**.
- Optimize recursive functions using **memoization or dynamic programming** when applicable.
Example: Tail Recursion Optimization
#include <stdio.h>
long factorialTail(int n, long result) {
if (n == 0) return result; // Base case
return factorialTail(n - 1, n * result);
}
int main() {
int num = 5;
printf("Factorial of %d is %ld\n", num, factorialTail(num, 1));
return 0;
}
Conclusion
Recursion is a powerful concept in C that helps break down complex problems into simpler ones. However, it should be used wisely to avoid performance issues and stack overflow errors! 🚀