Recursive Functions in C
A recursive function is a function that calls itself directly or indirectly to solve a problem. It is useful when a problem can be broken down into smaller subproblems of the same type.Key Concepts
- Every recursive function must have a base case — a condition that stops the recursion
- Without a base case, the function calls itself infinitely → stack overflow
Types of Recursion
| Type | Description |
|---|---|
| Direct Recursion | Function calls itself directly |
| Indirect Recursion | Function A calls Function B, and B calls A |
General Structure
Example 1: Factorial
factorial(5):
Example 2: Fibonacci Series
Advantages of Recursion
- Reduces code size for problems like tree traversals, factorial, Fibonacci
- Makes code more readable for mathematically recursive problems
- Naturally maps to divide-and-conquer algorithms
Disadvantages of Recursion
- Consumes more memory — each call adds a new frame to the call stack
- Can lead to stack overflow if the base case is missing or wrong
- Generally slower than an iterative solution for the same problem
Recursion vs Iteration
| Recursion | Iteration | |
|---|---|---|
| Approach | Function calls itself | Uses loops |
| Memory | More (call stack) | Less |
| Speed | Slower | Faster |
| Readability | Cleaner for recursive cases | Better for simple repeats |
| Risk | Stack overflow | Infinite loop |