Learn C++
#include "functions/recursion.hpp"

Recursion in C++

//concept

Recursion solves a problem by having a function call itself on smaller inputs: a base case that answers directly, and a recursive step that shrinks toward it. Factorial, tree traversals, and divide-and-conquer algorithms read almost as their mathematical definitions when written this way.

Every call consumes stack space for its frame, so depth is bounded (millions of frames overflow) and the base case is load-bearing — miss it and the program recurses until it crashes. C++ compilers perform tail-call optimization in simple cases, but never rely on it; prefer iteration for deep linear problems.

//how it works
1

Base case first

fact(0) = 1 answers without recursing — the anchor every call chain must be able to reach.

2

Shrink every step

fact(n) = n * fact(n-1) moves strictly toward the base case; a step that doesn't shrink loops forever.

3

Trust the contract

Assume the recursive call correctly solves the smaller instance — verify base case plus shrinkage, not the whole unfolding.

4

Mind the stack

Each live call holds a frame; recursion depth in the hundreds of thousands risks stack overflow — iterate deep linear recursions instead.

//example
#include <iostream>
 
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
 
int main() {
std::cout << fact(5) << std::endl;
return 0;
}
Output
120
1fact(5) doesn't hit the base case, so it returns 5 * fact(4), stacking frames down to fact(1).
2fact(1) hits n <= 1 and returns 1 with no further calls — the unwind begins.
3Results multiply back up (2*1, 3*2, ...) to 120, which prints.
//complexity
time O(n)
space O(n)

n calls each doing O(1) work, but n live stack frames at the deepest point.

//use cases
Tree and graph traversals where the data is itself recursive
Divide-and-conquer algorithms (mergesort, quicksort, binary search)
Backtracking searches that explore then undo each choice
Rewriting as iteration when depth threatens the stack

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.