C++ Recursion
A function is recursive when it calls itself. Recursion is a natural way to solve problems that contain smaller copies of themselves: a folder contains folders, a tree has sub-trees, and 5! is 5 × 4!.
The two essential parts
Every correct recursive function has:
- A base case — a simple input answered directly, without recursion.
- A recursive case — the problem is reduced to a smaller version of itself, which eventually reaches the base case.
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n <= 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case
}
int main() {
for (int i = 0; i <= 6; i++) {
cout << i << "! = " << factorial(i) << "\n";
}
cout << "20! = " << factorial(20) << "\n";
}0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
20! = 2432902008176640000
How the calls unfold
Each call gets its own copy of the parameters on the call stack. The calls go "down" until the base case, then the results come back "up". Indentation makes this visible:
#include <iostream>
#include <string>
using namespace std;
int sumTo(int n, int depth = 0) {
string pad(depth * 2, ' ');
cout << pad << "sumTo(" << n << ")\n";
if (n == 0) {
cout << pad << "-> 0\n";
return 0;
}
int result = n + sumTo(n - 1, depth + 1);
cout << pad << "-> " << result << "\n";
return result;
}
int main() {
sumTo(3);
}sumTo(3)
sumTo(2)
sumTo(1)
sumTo(0)
-> 0
-> 1
-> 3
-> 6
Warning: Without a reachable base case, a recursive function calls itself until the call stack runs out of space — a stack overflow, which crashes the program.
Recursion on data
Recursion is not only for numbers. Reversing a string, computing powers quickly, or searching a sorted array all have elegant recursive solutions:
#include <iostream>
#include <string>
using namespace std;
string reverse(const string& s) {
if (s.size() <= 1) return s;
return reverse(s.substr(1)) + s[0];
}
// fast exponentiation: b^e using about log2(e) multiplications
long long power(long long b, int e) {
if (e == 0) return 1;
long long half = power(b, e / 2);
return (e % 2 == 0) ? half * half : half * half * b;
}
int binarySearch(const int a[], int lo, int hi, int target) {
if (lo > hi) return -1; // not found
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) return binarySearch(a, mid + 1, hi, target);
return binarySearch(a, lo, mid - 1, target);
}
int main() {
cout << reverse("recursion") << "\n";
cout << power(3, 13) << "\n";
int sorted[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
cout << binarySearch(sorted, 0, 9, 23) << "\n";
cout << binarySearch(sorted, 0, 9, 7) << "\n";
}noisrucer
1594323
5
-1
Recursion vs iteration
Any recursive algorithm can be rewritten with loops, and vice versa. The naive recursive Fibonacci shows why the choice matters: it recomputes the same values over and over, while the loop version is linear.
#include <iostream>
using namespace std;
int calls = 0;
long long fibRecursive(int n) {
calls++;
if (n < 2) return n;
return fibRecursive(n - 1) + fibRecursive(n - 2);
}
long long fibLoop(int n) {
long long a = 0, b = 1;
for (int i = 0; i < n; i++) {
long long next = a + b;
a = b;
b = next;
}
return a;
}
int main() {
cout << fibRecursive(25) << " using " << calls << " calls\n";
cout << fibLoop(25) << " using a simple loop\n";
cout << fibLoop(90) << "\n";
}75025 using 242785 calls
75025 using a simple loop
2880067194370816120
| Recursion | Iteration |
|---|---|
| Elegant for tree-shaped problems (folders, parsing, divide-and-conquer) | Better for simple counting and linear processing |
| Uses stack space for each call | Constant extra memory |
| Can repeat work unless results are cached | Usually straightforward to make efficient |
Test yourself
What must every recursive function have to terminate?
- A loop
- A base case
- A global variable
- Two parameters
What is the result of factorial(4) with the definition in this lesson?
- 10
- 16
- 24
- 4
What happens when recursion never reaches its base case?
- It returns 0
- The compiler refuses the code
- A stack overflow eventually crashes the program
- It switches to a loop automatically