Learning Objectives
By the end of this topic you will be able to:
Define recursion and identify its two essential components
Trace recursive functions and identify the call stack during execution
Write recursive algorithms for factorial, Fibonacci and other problems
Compare recursion with iteration: advantages and disadvantages
Recursion Basics
What is Recursion?
A recursive function is one that calls itself. Every recursive solution must have two essential components:
1. Base case: a condition where the function does NOT call itself — stops the recursion.
2. Recursive case: the function calls itself with a simpler version of the problem — moves toward the base case.
Without a base case, the function calls itself infinitely, eventually causing a stack overflow — the call stack fills up and the program crashes.
Call Stack
The Call Stack in Recursion
Each time a function calls itself, a new stack frame is pushed onto the call stack containing: the function's local variables, the return address, and the current value of parameters. When the base case is reached, frames are popped in reverse (LIFO) and results are passed back up the chain.
Stack depth = number of recursive calls. For factorial(n), depth = n+1 frames. For large n this can cause a stack overflow — which is why iterative solutions are sometimes preferred for deeply recursive problems.
A stack overflow occurs when the call stack runs out of space due to too many nested recursive calls. This can happen when the base case is incorrect or n is very large.
Common Mistakes
Don't Lose Marks
!
Missing the base case in a recursive solution — every recursive function must have a base case that terminates the recursion. A recursive case alone produces infinite recursion and stack overflow. Always identify and state the base case explicitly in exam answers.
!
Tracing the recursion in the wrong order — recursive calls go DOWN first until the base case, then results propagate BACK UP. Students often show values being computed during the descent rather than the ascent. The computation happens when frames unwind (are popped), not when they're pushed.
!
Saying recursion is always better than iteration — OCR questions specifically test understanding of trade-offs. Recursion uses more memory (stack frames) and risks stack overflow. Always mention both advantages and disadvantages when asked to compare.