M11 · Recursion

Recursion and the Call Stack: Base Cases, Frames and Depth Limits

A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a case small enough to answer directly. Every call that has started but not finished keeps a frame on the call stack, so the depth of the recursion is a real memory cost with a hard limit.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M11 Recursion · 1 of 1 lessons available

You will be able to

  • Identify the base case and the recursive case of a recursive function, and explain why every call must move towards a base case.
  • Trace the call stack of a recursive function: which frames exist at each moment, what each one stores, and the order in which they return.
  • Compare linear recursion with halving recursion by depth, number of calls and running time.
  • Explain what happens when recursion is too deep in C#, Python, Java and C++, and how to avoid it.
  • Recognise integer overflow in a recursive computation and handle it per language.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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 long inside checked(...), which throws OverflowException instead of silently wrapping (C# arithmetic is unchecked by default).
  • Java uses Math.multiplyExact, which throws ArithmeticException on 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 b breaks power(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 in half first.
  • 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, Java StackOverflowError, .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.

Full implementation

Both recursive powers in four languages, each checked against one shared fixture (zero exponent, zero and negative bases, results up to the 64-bit limit) and 2,000 random cases compared with an exact reference (BigInteger, Python ints or a checked loop); the C#, Java and C++ tests also confirm that a result past 64 bits throws instead of wrapping, and the Python and Java tests trigger a real RecursionError and StackOverflowError.

namespace Bekadan.Dsa.Examples.Recursion;
 
/// <summary>
/// Integer power b^e computed recursively, two ways. Both use 64-bit integers and
/// <c>checked</c> multiplication, so a result that does not fit throws
/// <see cref="OverflowException"/> instead of silently wrapping around.
/// </summary>
public static class RecursivePower
{
    /// <summary>Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.</summary>
    public static long Linear(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long rest = Linear(b, e - 1);
        return checked(b * rest);
    }
 
    /// <summary>Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.</summary>
    public static long Squaring(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long half = Squaring(b, e / 2);
        if (e % 2 == 0)
            return checked(half * half);
        return checked(half * half * b);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Recursion/RecursivePower.cs

"""Integer power b**e computed recursively, two ways.
 
Python integers have arbitrary precision, so these never overflow; the other three
languages use 64-bit integers and check every multiplication. What Python does limit
is recursion depth: linear recursion needs e + 1 frames, and the interpreter raises
RecursionError past sys.getrecursionlimit() (1000 by default).
"""
 
 
def power_linear(b: int, e: int) -> int:
    """Linear recursion: one call per unit of e. Θ(e) time and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    rest = power_linear(b, e - 1)
    return b * rest
 
 
def power_squaring(b: int, e: int) -> int:
    """Recursion by squaring: the exponent halves on every call. Θ(log e) calls and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    half = power_squaring(b, e // 2)
    if e % 2 == 0:
        return half * half
    return half * half * b

Tested on CPython 3.14.0 · examples/python/dsa_examples/recursive_power.py

package dev.bekadan.dsa.recursion;
 
/**
 * Integer power b^e computed recursively, two ways. Both use 64-bit {@code long} and
 * {@link Math#multiplyExact(long, long)}, so a result that does not fit throws
 * {@link ArithmeticException} instead of silently wrapping around.
 */
public final class RecursivePower {
    private RecursivePower() {
    }
 
    /** Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack. */
    public static long linear(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long rest = linear(b, e - 1);
        return Math.multiplyExact(b, rest);
    }
 
    /** Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack. */
    public static long squaring(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long half = squaring(b, e / 2);
        if (e % 2 == 0) {
            return Math.multiplyExact(half, half);
        }
        return Math.multiplyExact(Math.multiplyExact(half, half), b);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/recursion/RecursivePower.java

#pragma once
 
#include <cstdint>
#include <limits>
#include <stdexcept>
 
namespace bekadan::dsa {
 
// Signed overflow is undefined behaviour in C++, so check before multiplying
// (the bounds test from SEI CERT rule INT32-C).
inline std::int64_t checked_multiply(std::int64_t a, std::int64_t b) {
    constexpr auto max = std::numeric_limits<std::int64_t>::max();
    constexpr auto min = std::numeric_limits<std::int64_t>::min();
    const bool overflows = a > 0 ? (b > 0 ? a > max / b : b < min / a)
                                 : (b > 0 ? a < min / b : a != 0 && b < max / a);
    if (overflows) throw std::overflow_error("power does not fit in 64 bits");
    return a * b;
}
 
// Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.
inline std::int64_t power_linear(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t rest = power_linear(b, e - 1);
    return checked_multiply(b, rest);
}
 
// Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.
inline std::int64_t power_squaring(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t half = power_squaring(b, e / 2);
    if (e % 2 == 0) return checked_multiply(half, half);
    return checked_multiply(checked_multiply(half, half), b);
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/recursive_power.hpp

References