C Recursion – A Complete Beginner's Guide
Recursion is a process in which a function calls itself to solve a smaller part of the problem. It’s commonly used for tasks that can be divided into similar sub-tasks like calculating factorials, traversing trees, or solving puzzles.
What is Recursion in C?
A recursive function is a function that calls itself, either directly or indirectly, to solve a problem.
Syntax of Recursive Function
return_type function_name(parameters) {
if (base_condition)
return result;
else
return function_name(modified_parameters);
}
Example: Factorial using Recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1; // base case
else
return n * factorial(n - 1); // recursive call
}
int main() {
int result = factorial(5);
printf("Factorial = %d\n", result);
return 0;
}
Output:
Factorial = 120
How Recursion Works (Step-by-Step for factorial(3))
factorial(3)
→ 3 * factorial(2)
→ 2 * factorial(1)
→ 1 * factorial(0)
→ 1 (base case)
→ 1 * 1 = 1
→ 2 * 1 = 2
→ 3 * 2 = 6
Example: Fibonacci using Recursion
#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int i, n = 7;
printf("Fibonacci series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Output:
Fibonacci series: 0 1 1 2 3 5 8
Base Case is Important
Without a base case, the function would keep calling itself and cause a stack overflow error.
Add Your Heading Text Here
Best Practice | Why It Matters |
---|---|
Always define a base case | Prevents infinite recursion |
Use recursion for divide-and-conquer problems | Simplifies the logic |
Prefer iteration when possible | Recursion uses more memory (call stack) |
Test with small inputs first | Ensures your logic is correct early |
Common Mistakes in Recursion
Mistake | Problem |
---|---|
Missing base case | Leads to infinite calls |
Modifying parameters incorrectly | Gives wrong results or crashes |
Using recursion unnecessarily | Wastes memory and processing time |
Pros and Cons of Recursion
Pros | Cons |
---|---|
Simplifies complex problems | High memory usage (call stack) |
Makes code elegant and clean | Can be slower than iteration |
Useful in tree/graph problems | Hard to debug if logic is wrong |