

C++ programmers employ recursion, which is a complicated tool. It enables you do hard things like go through a binary tree or a maze with just few lines of code. But with great power comes the responsibility to maintain the "call stack" in order. This guide explains how recursion works in C++, includes examples, and illustrates how to speed it up.
|
Type |
Logic | Efficiency |
|
Non-Tail |
n * fact(n-1) (Multiplication happens after return) |
Uses $O(n)$ stack space. |
| Tail | fact(n-1, n * accumulator) (Last call is just the function) |
Uses $O(1)$ stack space (if optimized). |
|
Advantages |
Disadvantages |
|
Clean Code: Reduces code length for complex algorithms. |
Memory Usage: High stack consumption. |
|
Data Structures: Essential for Trees and Graphs. |
Speed: Usually slower than iteration due to call overhead. |
| Logic: Very intuitive for problems with sub-problems. |
Debugging: Harder to trace than loops. |
|
Feature |
Recursion | Iteration |
| Definition | Function calls itself. |
Repeated execution of a block (loops). |
|
Termination |
Base case is met. | Loop condition becomes false. |
| Memory | High (Stack frames). |
Low (Fixed variables). |
|
Code Size |
Smaller. |
Larger. |
