01 / 21

Writing Recursive
Functions in C++

Master the art of functions that call themselves: understand base cases, recursive steps, and how to translate mathematical definitions into elegant C++ code.

C++ Computer Science

What Is Recursion?

Recursion is a problem-solving technique where a function solves a problem by calling itself with a smaller or simpler version of the same problem. Each call brings the problem closer to a base case: a condition simple enough to answer directly without further recursion.

Anatomy of a Recursive Function

Every correct recursive function has exactly two essential parts:

Base Case
The condition where the function stops calling itself and returns a known value directly. Without it, recursion never ends.
Recursive Step
The function calls itself with a smaller or simpler input, moving closer to the base case with every call.

Visualizing the Call Stack

Each recursive call adds a new stack frame. When the base case is reached, frames unwind in reverse order, returning values back up the chain.

factorial(4) factorial(3) factorial(2) factorial(1) factorial(0) = 1 BASE CASE calls calls calls calls returns 24 returns 6 returns 2 returns 1 returns 1 UNWIND

The Two Rules of Recursion

1
Every recursive function must have a base case. The base case is a condition that returns a value directly, without making another recursive call. It acts as the "exit door" for the recursion.
2
Every recursive call must move toward the base case. The argument passed to the recursive call must be "smaller" or "closer" to the base case than the current argument. This guarantees termination.

Recursion vs. Iteration

Recursion Iteration
Mechanism Function calls itself Loop repeats a block
Termination Base case reached Loop condition false
Memory Uses stack frames Constant (usually)
Readability Mirrors math definitions More explicit control
Best for Trees, divide & conquer Simple counting, arrays

How to Write a Recursive Function

1
Define the function signature. Decide the return type, name, and parameters. What does it take in and give back?
2
Identify the base case(s). What is the simplest input? What should the function return for it? Write this as an if statement first.
3
Write the recursive step. Assume the function already works for smaller inputs. Express the current answer in terms of a recursive call on a smaller input.
4
Verify progress. Confirm that every recursive call uses an argument closer to the base case. Trace through 2-3 small examples mentally.

Example 1: Factorial

The factorial of \( n \) is defined as: \( n! = n \times (n-1)! \) with base case \( 0! = 1 \).

int factorial(int n) { if (n == 0) return 1; // base case return n * factorial(n - 1); // recursive step }

Tracing factorial(4)

factorial(4) = 4 * factorial(3) factorial(3) = 3 * factorial(2) factorial(2) = 2 * factorial(1) factorial(1) = 1 * factorial(0) factorial(0) = 1 (base case!) 1 1 * 1 = 1 2 * 1 = 2 3 * 2 = 6 4 * 6 = 24 Result: 24

Example 2: Sum of Digits

Write a function that returns the sum of the digits of a positive integer. For example, sumDigits(123) should return \( 1 + 2 + 3 = 6 \).

int sumDigits(int n) { if (n == 0) return 0; // base case return (n % 10) + sumDigits(n / 10); // recursive step }

Example 3: Fibonacci Sequence

The Fibonacci sequence is defined by \( F(0) = 0 \), \( F(1) = 1 \), and \( F(n) = F(n-1) + F(n-2) \) for \( n \geq 2 \). Notice: two base cases.

int fib(int n) { if (n == 0) return 0; // base case 1 if (n == 1) return 1; // base case 2 return fib(n - 1) + fib(n - 2); // two recursive calls }

Fibonacci Call Tree

Each call branches into two sub-calls, creating a tree of calls. This shows why naive Fibonacci is exponentially slow.

fib(4) fib(3) fib(2) fib(2) fib(1)=1 fib(1)=1 fib(0)=0 fib(1)=1 fib(0)=0 9 calls for fib(4)! Grows exponentially

Example 4: Power Function

Compute \( x^n \) recursively using the identity \( x^n = x \times x^{n-1} \) with base case \( x^0 = 1 \).

double power(double x, int n) { if (n == 0) return 1.0; // base case return x * power(x, n - 1); // recursive step }

When You Need Multiple Base Cases

Some recursive definitions reach the bottom in more than one way. You need a base case for every way the recursion can terminate.

Single Base Case
Factorial: only one recursive call per step, so only \( n = 0 \) needs handling.
Two Base Cases
Fibonacci: two recursive calls (\( n-1 \) and \( n-2 \)), so both \( n = 0 \) and \( n = 1 \) need handling.
Structural Base Case
String/array recursion: base case is often an empty string or size 0, not a numeric value.

Common Mistakes

Missing Base Case
Forgetting to include a base case causes infinite recursion and a stack overflow. Always write the base case first.
No Progress Toward Base
Calling the function with the same or larger argument: f(n) calls f(n) instead of f(n - 1). Infinite loop.
Wrong Return Value
Returning the wrong value in the base case. For factorial, returning 0 instead of 1 makes every result 0.
Not Returning Recursive Call
Writing factorial(n - 1) without return. The result is computed but discarded, giving undefined behavior.

Recursive Function Cheat Sheet

Function Base Case Recursive Step
Factorial \( 0! = 1 \) \( n \times (n-1)! \)
Sum of Digits \( n = 0 \to 0 \) \( n \% 10 + f(n / 10) \)
Fibonacci \( F(0)=0,\; F(1)=1 \) \( F(n-1) + F(n-2) \)
Power \( x^0 = 1 \) \( x \times x^{n-1} \)
String Length \( \text{len}("") = 0 \) \( 1 + \text{len}(\text{rest}) \)

Question 1 of 5

What are the two essential parts of every correct recursive function?

Question 2 of 5

What does the following function return when called as mystery(5)?

Question 3 of 5

A student writes this recursive factorial function. What is wrong?

Question 4 of 5

Why does the Fibonacci function need two base cases (\( n = 0 \) and \( n = 1 \)) instead of just one?

Question 5 of 5

Which of the following correctly computes the sum of elements in an array recursively?