Mental model
A recursive function answers a question by asking itself a smaller version of the same question, and stops when the question is small enough to answer on the spot. Two parts, always:
- The base case: an input answered directly, without another call.
- The recursive case: an input answered by combining the result of one or more calls on smaller inputs.
Here is integer power, power(b, e) = bᵉ, written the most direct way:
power(b, e):
if e == 0: return 1 # base case
return b * power(b, e - 1) # recursive case: e - 1 is smaller
Each call works on a smaller exponent, so after e calls the exponent reaches 0 and the recursion stops. A recursive function is correct when (1) the base cases are right, (2) the recursive case is right assuming the smaller calls return correct answers, and (3) every chain of calls reaches a base case. That is a proof by induction, written as code.
What the call stack holds
A call does not finish before the call it makes has returned. While power(2, 3) waits for
power(2, 2), it must remember its own b, its own e, and where to continue. The runtime keeps
that in a stack frame: one per call that has started and not yet returned, stacked in the order
the calls were made.
power(2, 3) waits: needs power(2, 2)
power(2, 2) waits: needs power(2, 1)
power(2, 1) waits: needs power(2, 0)
power(2, 0) base case: returns 1
power(2, 1) resumes: 2 * 1 = 2, returns
power(2, 2) resumes: 2 * 2 = 4, returns
power(2, 3) resumes: 2 * 4 = 8, returns
The stack grows while calls go down and unwinds as they return, innermost first. Every
frame has its own e: the variables of a waiting call are not overwritten by the call it made.
In the lab, active frames stand on the front row, left to right by depth; a frame that returns
moves to the row behind, labelled with its return value. The work happens on the way back up:
each multiplication runs only after the inner call has returned.
Depth is a cost: linear versus halving recursion
The version above needs e + 1 frames at its deepest moment and e multiplications. A better recursive case halves the problem instead of shrinking it by one:
power(b, e):
if e == 0: return 1
half = power(b, e / 2) # integer division
if e is even: return half * half
return half * half * b
The exponent goes 13 → 6 → 3 → 1 → 0, so the depth is ⌊log₂ e⌋ + 2 frames (1 when e = 0), and the number of multiplications is the number of bits of e plus the number of 1-bits. Run the Linear and Squaring presets with the same input and compare the Max stack depth metric.
| Version | Calls = max depth | Multiplications | Time | Stack |
|---|---|---|---|---|
| Linear | e + 1 | e | Θ(e) | Θ(e) frames |
| Squaring | ⌊log₂ e⌋ + 2 | between ⌊log₂ e⌋ + 2 and 2(⌊log₂ e⌋ + 1) | Θ(log e) | Θ(log e) frames |
The costs assume each multiplication is O(1), which holds for fixed-width integers. With Python's arbitrary-precision integers the numbers grow, and later multiplications cost more.
Both versions make one recursive call per frame (linear recursion in the structural sense). A function that calls itself twice, like naive Fibonacci, forms a recursion tree and can make exponentially many calls while the stack depth stays linear; that is the subject of From recursion to dynamic programming.
The stack limit
The call stack is a fixed region of memory per thread. When recursion goes deeper than it allows, the program fails. The Stack overflow preset simulates a stack of 12 frames and asks for 21. Real limits are not counted in frames but in bytes (except Python's), and they depend on the platform, the build and settings. Treat the numbers below as typical defaults, not guarantees.
| Language | Limit | What happens when you exceed it |
|---|---|---|
| Python | A frame count: sys.getrecursionlimit(), 1000 by default |
RecursionError, a normal exception you can catch |
| Java | Thread stack size in bytes, set with -Xss or the Thread constructor; the default is platform-dependent (commonly about 1 MB on 64-bit systems) |
StackOverflowError. It can be caught, but the program may be in an inconsistent state; do not rely on it |
| C# / .NET | Thread stack size in bytes; the main thread's size comes from the OS and the executable (commonly 1 MB on Windows, often 8 MB on Linux), new threads can request a size | The process is terminated: since .NET Framework 2.0 a stack overflow cannot be caught with try/catch |
| C++ | The OS thread stack (commonly 1 MB on Windows, 8 MB on Linux via ulimit -s) |
Nothing in the language detects it: in practice the program crashes (a segmentation fault or access violation) |
How many frames fit depends on how large each frame is: locals, arguments, saved registers and
compiler choices. A frame of power is small, so tens of thousands may fit, but a function with
a large local array may fit only hundreds.
Avoiding deep recursion. If the depth can grow with the input size (a linked list of a
million nodes, a degenerate tree, linear power with a huge exponent), use a loop or an explicit
stack, or change the recursion so it halves the problem. Raising Python's limit with
sys.setrecursionlimit only moves the problem: the interpreter's own C stack can still run out,
and that is a crash rather than an exception. Tail calls do not save you portably: Python and
Java never eliminate them, the .NET JIT and C++ optimisers sometimes do, and none of them
guarantees it.
Overflow is a separate limit
A recursion can be shallow and still produce a number too large for its type. 2⁶² fits in a signed 64-bit integer; 2⁶³ does not. The four implementations handle that differently:
- C# computes in
longinsidechecked(...), which throwsOverflowExceptioninstead of silently wrapping (C# arithmetic is unchecked by default). - Java uses
Math.multiplyExact, which throwsArithmeticExceptionon overflow (plain*wraps). - C++ checks before multiplying, because signed overflow is undefined behaviour: the compiler may assume it never happens, so you cannot test for it afterwards.
- Python integers have arbitrary precision:
power(2, 63)is simply 9223372036854775808.
The lab rejects inputs whose result does not fit in 64 bits, so the trace always matches what the listings compute.
The teaching implementation
Each language has Linear and Squaring (or power_linear and power_squaring) with the same
structure as the lab: base case, recursive call, combine. All four read one shared fixture (zero
exponent, zero and negative bases, results right up to the 64-bit limit) and compare 2,000 random
cases with an exact reference. The Python test triggers a real RecursionError with
power_linear(1, limit + 100), and the Java test catches a real StackOverflowError; the same
experiment in C# or C++ would take the whole test process down, which is exactly the point of the
table above.
Common mistakes
- No base case, or one that is never reached.
power(b, e - 2)from an odd e skips 0 and recurses forever (until the stack runs out). - A base case that is right for some inputs only.
if e == 1: return bbreakspower(b, 0). - Forgetting to use the result. Calling
power(b, e - 1)without returning or combining it. - Calling twice when once is enough.
power(b, e / 2) * power(b, e / 2)computes the same value twice and turns Θ(log e) into Θ(e) calls; store it inhalffirst. - Recursing on input-sized depth in production code (lists, unbalanced trees) where a loop would do.
Edge cases
- e = 0: one frame, no multiplication, result 1 (including 0⁰, which these functions define as 1, like most programming languages' power functions).
- Negative bases: the sign comes from the odd steps; (−2)⁷ = −128.
- Negative exponents are rejected: the result would not be an integer.
Worked practice
1. How many frames does linear power(3, 9) need at its deepest point, and how many does squaring need?
Answer
Linear: 10 (e = 9, 8, …, 0). Squaring: e goes 9 → 4 → 2 → 1 → 0, so 5 frames, which matches ⌊log₂ 9⌋ + 2 = 3 + 2.
2. sum(n) returns n + sum(n - 1) with base case sum(0) = 0. Which frame finishes first, and what does it return?
Answer
sum(0), the deepest frame, finishes first and returns 0. Frames return in the reverse order of
their calls: sum(1) returns 1, sum(2) returns 3, and so on up to the original call.
3. A recursive function works on a linked list of length n, one node per call. Why can it crash for large n even though it is correct?
Answer
Its depth is n frames. For a large enough n the thread stack runs out: a RecursionError in
Python (beyond about 1,000 frames by default), a StackOverflowError in Java, a terminated process
in .NET, a crash in C++. Rewrite it as a loop.
Summary
- Recursion = base case + recursive case that moves towards it.
- Every unfinished call holds a stack frame; the stack unwinds innermost first.
- Depth is a real cost: linear recursion needs Θ(n) frames, halving recursion Θ(log n).
- Stack limits are platform-dependent; Python raises
RecursionError, JavaStackOverflowError, .NET terminates, C++ crashes. Use loops for input-sized depth. - Overflow is separate from depth: check it (
checked,multiplyExact, a pre-check in C++) or use arbitrary-precision integers.