3.4 Recursion
Recursion: -
- Recursion is the process in which a function calls itself either directly or indirectly to solve a problem.
- Recursive function breaks the problem down into smaller, identical sub-problems, solves them, and combines the results.
- A recursive function has two parts:
a) Base Case: Every
recursive function must have a condition to stop calling itself, otherwise it
will result in infinite recursion and eventually a stack overflow.
b) Recursive Case: The
part where the function calls itself with a smaller or simpler input.
Example: -
Output: -
Advantages of Recursion: -
- Makes code shorter and cleaner for problems like factorial, Fibonacci, GCD, and tree traversal.
- Useful for problems that have self-similar structures (like Divide and Conquer algorithms).
Disadvantages of Recursion: -
- Can lead to high memory usage due to function call stack.
- Slower compared to iterative solutions in some cases.
- Risk of stack overflow if base case is not reached.