Learning pathOriginal reference
Lesson 12 of 12

Optional: recursion and pending work

Trace a base case, the return journey, total calls, and peak call depth.

A smaller problem and a stopping case

Recursion means a function calls itself directly or indirectly. For factorial, 0! = 1 is the base case and n! = n × (n − 1)! supplies a smaller problem. Every recursive step must move toward a base case under the stated input domain.

factorial(3) waits for factorial(2), which waits for factorial(1), which waits for factorial(0). The results then return as 1, 1, 2, and 6. Each unfinished call has its own n and local state.

C++23
// Complete C++23 program. Input: 0 <= n <= 20.
#include <iostream>
long long factorial(int n) {
    if (n == 0) return 1;
    long long smaller = factorial(n - 1);
    return n * smaller;
}
int main() {
    int n = 0;
    std::cin >> n;
    std::cout << factorial(n) << '\n';
}

Time and simultaneous calls answer different questions

Factorial makes n + 1 calls including its base case, so time is O(n + 1). Up to n + 1 calls can be pending together, giving O(n + 1) auxiliary space in the ordinary call-stack model. An iterative factorial uses a running product and O(1) auxiliary space.

The call stack models pending function work; C++ does not mandate a particular physical stack layout or promise elimination of recursion. Code after a recursive call runs on the return journey, not before the smaller call finishes.

Branching can repeat work

Naive Fibonacci computes F(n − 1) and F(n − 2) independently. For F(5), F(3) is recomputed in separate branches. A valid upper bound is O(2ⁿ) time, but this is not a claim that Θ(2ⁿ) is the tight bound or that the exact call count is 2ⁿ.

Only one branch executes at a time, so peak pending depth is linear, not exponential. A missing base case, a recursive call with the same positive input, or an out-of-domain negative input can break termination.

Value or reference?

The helper executes x += 10. Compare the caller’s value before and after the call.

Caller before5
Inside helper15
Caller after5

The parameter is a copy. Changing it leaves the caller’s variable untouched.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

Why can naive recursive Fibonacci have exponential total work but only linear peak call depth?

Choose an answer
Try it yourself

Turn the idea into code

A helper prints n, recursively processes n − 1, then prints n again. It returns immediately for zero. Predict the output for n = 3 and implement it for 0 ≤ n ≤ 20.

Give me a hint

Write a separate line for each unfinished call. The second print waits for the smaller call to return.

Show the explained solution

The output is 3, 2, 1, 1, 2, 3 on separate lines. There are n + 1 calls and 2n output lines, so time and ordinary call-stack space are O(n + 1). For zero, it prints no lines.

C++23
// Complete C++23 program. Input: 0 <= n <= 20.
#include <iostream>
void downAndUp(int n) {
    if (n == 0) return;
    std::cout << n << '\n';
    downAndUp(n - 1);
    std::cout << n << '\n';
}
int main() {
    int n = 0;
    std::cin >> n;
    downAndUp(n);
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.