Module 4 · Functions, Recursion and Storage Classes — topic 2 of 3
Recursion
A recursive function calls itself on a smaller version of the problem until it reaches a base case. Learn to design recursive functions, trace the call stack, and know when iteration is better.
Learning objectives
- Write recursive functions with correct base and recursive cases
- Trace recursive calls using the call stack
- Compare recursion and iteration in clarity, memory and speed
Definition
Recursion is a technique in which a function calls itself, directly or indirectly. A correct recursive function has at least one base case that returns without recursing and a recursive case that moves the input strictly closer to a base case.
Introduction
Some problems are naturally defined in terms of themselves: the factorial of n is n times the factorial of n − 1; a folder's size is its files plus the sizes of its sub-folders. Recursion lets the code mirror that definition directly.
Each call gets its own copy of parameters and local variables, stored in a stack frame. When the base case is reached, the calls return one by one, combining their results.
Why it matters
Recursion is essential for trees, graphs, divide-and-conquer algorithms (merge sort, quick sort, binary search) and backtracking — all core DSA topics.
Tracing recursion by hand is a common written-exam question, and missing base cases are a common cause of crashes.
Detailed explanation
Design in two steps: 1. Base case — the smallest input you can answer directly (e.g. 0! = 1). 2. Recursive case — express the answer using a smaller input (e.g. n! = n × (n−1)!).
Every call pushes a frame on the call stack. Deep recursion (hundreds of thousands of calls) can exhaust the stack — a *stack overflow* — which usually crashes the program. Typical default stacks are 1–8 MB.
Some recursive solutions recompute the same subproblems many times. Naive Fibonacci makes about 1.6ⁿ calls; an iterative loop or memoisation reduces that to n steps.
A call is tail recursive when the recursive call is the last action. Compilers *may* optimise tail calls into loops at higher optimisation levels, but the C standard does not require it.
Syntax
- Check the base case before recursing.
- Each recursive call must move toward the base case.
- Return the recursive result; don't just call the function.
Code examples
Factorial
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 20! = 2432902008176640000
20! is the largest factorial that fits in an unsigned 64-bit integer.
Sum of digits
35
More examples
Tower of Hanoi and recursive binary search
Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C 7 moves 42 at index 4 10 at index -1
Step-by-step explanation
- To move n disks from A to C, first move n − 1 disks out of the way to B (first recursive call).
- Then move the largest disk directly to C and count the move.
- Finally move the n − 1 disks from B onto C (second recursive call). n disks need 2ⁿ − 1 moves: 7 for n = 3.
bsearch_rechalves the search range each call;lo > hiis the base case meaning “not found”.lo + (hi - lo) / 2computes the midpoint without the overflow risk of(lo + hi) / 2.
Expected output
Running “Tower of Hanoi and recursive binary search” prints exactly:
Practical applications
- File managers compute folder sizes by recursing into sub-folders.
- Compilers parse nested expressions with recursive-descent parsers.
- Sorting libraries use recursive quick sort and merge sort.
Best practices
- Write and test the base case first.
- Prefer iteration when recursion depth could be large or the loop is just as clear.
- Use memoisation or a loop when subproblems repeat (Fibonacci).
Common mistakes
No base case
Avoid
Prefer
Without a base case the recursion never stops and the stack overflows.
Ignoring the recursive result
Avoid
Prefer
The result of the recursive call must be used to build the answer.
Important notes
- Recursion depth for a balanced divide-and-conquer algorithm is about log₂ n — fine even for huge n. Linear recursion depth (one call per element) can overflow for large inputs.
- Signed integer overflow inside a recursive computation (e.g.
intfactorial beyond 12!) is undefined behaviour; use wider unsigned types.
Key takeaways
- Recursion = base case + recursive case that shrinks the problem.
- Each call has its own stack frame; too many frames overflow the stack.
- Naive recursion can repeat work exponentially; iterate or memoise.
Try it yourself
- 1Write a recursive function to compute xⁿ using x^(n/2) for even n (fast exponentiation).
- 2Write recursive and iterative Fibonacci functions and count how many calls the recursive one makes for n = 25.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
8 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat happens if a recursive function has no base case?
- ModerateWhat is printed?