B2.4.4 · Programming algorithms
Concept of recursion
By the end you can
Explain base cases, recursive steps, convergence, and stack overflow risks compared to iteration.
is a problem-solving technique where a function solves a problem by calling itself with a smaller instance of the same problem. Any algorithm that can be solved iteratively with a loop can also be solved recursively, and vice versa.
The two essential components#
Every valid recursive function must have two distinct parts:
- The Base Case: The trivial stopping condition where the answer is known directly without any further recursive calls. Without a base case, the function calls itself indefinitely until all call stack memory is exhausted.
- The Recursive Step: The part of the function where it calls itself, passing a parameter that is closer to the base case (e.g.
fact(n - 1)).
// Factorial: n! = n * (n - 1)!
public int factorial(int n) {
// 1. Base case
if (n <= 1) {
return 1;
}
// 2. Recursive step
return n * factorial(n - 1);
}Recursion versus Iteration#
While recursion provides elegant solutions for nested trees and divide-and-conquer algorithms, it carries physical memory costs:
- Memory overhead: Each recursive invocation pushes a new stack frame onto the call stack. For deep recursion ($n = 10,000$), this triggers a
StackOverflowError. - Execution speed: Function call overhead (pushing/popping frames, setting up parameters) makes simple recursion slightly slower than a hardware-optimized iterative
forloop.
Check yourself
Recursion foundations
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 9 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Explain the two essential components required in every recursive algorithm: the base case and the recursive step, and their role in stack memory.
[4]Explain: Give reasons: say what happens AND why, or how one thing causes another.
2.Compare recursion and iteration in terms of memory overhead, code clarity, and risk of termination failures.
[3]Compare: Similarities and differences, about both things, point by point.
3.Describe the consequence if a programmer forgets to include a base case in a recursive function.
[2]Describe: A detailed account: say what happens, step by step if it is a process.
In a nutshell
- Recursion is a technique where a function calls itself with smaller sub-problems until reaching a base case.
- Every recursive algorithm requires a base case to terminate and a recursive step that converges towards the base case.
- Missing or unreachable base cases cause infinite recursion, crashing with a StackOverflowError.
- Each active call pushes an activation record onto the call stack, consuming O(n) auxiliary stack memory.
