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.
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:
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.
The Two Rules of Recursion
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
Example 1: Factorial
The factorial of \( n \) is defined as: \( n! = n \times (n-1)! \) with base case \( 0! = 1 \).
Tracing factorial(4)
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 \).
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.
Fibonacci Call Tree
Each call branches into two sub-calls, creating a tree of calls. This shows why naive Fibonacci is exponentially slow.
Example 4: Power Function
Compute \( x^n \) recursively using the identity \( x^n = x \times x^{n-1} \) with base case \( x^0 = 1 \).
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.
Common Mistakes
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?