Recursion
What recursion is and its three essential features, writing and tracing recursive functions and procedures, how the call stack makes recursion work, and when recursion is the right choice.
Recursion
A recursive subroutine calls itself on a smaller problem, until it reaches a case it can answer at once.
A recursive subroutine is defined in terms of itself: it calls itself. It must have two parts:
- a base case, which returns an answer without calling itself
- a general case, which calls itself with a smaller problem that moves towards the base case.
When the base case is reached, the calls finish in reverse order. Each one returns its result to its caller. This is unwinding.
| Recursion | |
|---|---|
| Use it when | a problem is made of smaller copies of itself, like a tree or a factorial |
| Good | the code is short and clear |
| Costs | each call uses memory; it is often slower than a loop; too many calls overflow the stack |
Example:Factorial(3) = 3 × 2 × 1 × Factorial(0) = 3 × 2 × 1 × 1 = 6.
FUNCTION Factorial(n : INTEGER) RETURNS INTEGER IF n = 0 THEN RETURN 1 // base case ELSE RETURN n * Factorial(n - 1) // general case ENDIF ENDFUNCTION OUTPUT Factorial(3) // Factorial(3) // = 3 * Factorial(2) // = 3 * 2 * Factorial(1) // = 3 * 2 * 1 * Factorial(0) // = 3 * 2 * 1 * 1 = 6
The three essential features
Recursion needs three things: a call to itself, a base case, and calls that move towards that base case.
Exams often ask for the three essential features of recursion:
- The subroutine calls itself: that call is the general case.
- It has a base case: a stopping condition that returns without calling itself.
- Each call changes the state and moves towards the base case, so the base case is reached in the end.
Then the calls unwind.
SumTo(n) adds n, n - 1 and so on down to 0. Which recursive call works?
| Recursive call | What happens |
|---|---|
SumTo(n - 1) | works |
SumTo(n + 1) | moves away from 0 |
SumTo(n - 2) | moves towards 0, but from an odd n it jumps over it: 5, 3, 1, -1 |
Watch out:The last two go on calling until the stack overflows.
FUNCTION SumTo(n : INTEGER) RETURNS INTEGER IF n = 0 THEN RETURN 0 // base case ELSE RETURN n + SumTo(n - 1) // general case ENDIF ENDFUNCTION DECLARE Number : INTEGER INPUT Number OUTPUT SumTo(Number)
Writing a recursive function
To write a recursive function, find the simplest case first. Then build each bigger answer from a smaller one.
To write a recursive function, answer two questions.
| Question | Its answer is the... |
|---|---|
| What is the simplest case, whose answer you know at once? | base case |
| How is the answer for a bigger case built from the answer for a smaller one? | general case |
DigitSum adds the digits of a number.
- Base case: a number below 10 is its own answer.
- General case: take the last digit,
Number MOD 10, and add the digit sum of the rest,Number DIV 10. The rest has one digit fewer.
MOD gives the remainder after dividing, and DIV gives the whole-number result.
Watch out:Write it as a FUNCTION with RETURNS. Call it only inside an expression, never with CALL: the value it returns takes the call's place.
FUNCTION DigitSum(Number : INTEGER) RETURNS INTEGER DECLARE Result : INTEGER IF Number < 10 THEN Result ← Number // base case ELSE Result ← Number MOD 10 + DigitSum(Number DIV 10) ENDIF RETURN Result ENDFUNCTION DECLARE Value : INTEGER INPUT Value OUTPUT DigitSum(Value)
Writing a recursive procedure
In a recursive procedure, work before the call happens on the way down; work after it happens on the way back.
A procedure can call itself too. Its call is a complete statement, starting with CALL.
Its base case can do nothing. In Show, when n is 0 the IF is false, so that call simply ends.
Where the work goes matters:
| A statement placed... | runs... | Show(3) outputs |
|---|---|---|
before the recursive CALL | on the way down, as each call is made | 3 2 1 |
after the recursive CALL | on the way back, as the calls unwind, so in reverse order | 1 2 3 |
Example:An in-order traversal of a binary tree is written this way, with its OUTPUT between two recursive calls.
PROCEDURE Show(n : INTEGER) IF n > 0 THEN OUTPUT n CALL Show(n - 1) ENDIF ENDPROCEDURE DECLARE Start : INTEGER INPUT Start CALL Show(Start)
Tracing a recursive function
Trace a recursive function in two parts: one row per call on the way down, then rows on the way back up.
Exam papers trace recursive functions call by call.
- Winding, on the way down: each call gets a row with its parameters. Its Result is still an expression, waiting for the call it has just made.
- Base case: the call that reaches it returns its value at once.
- Unwinding, back up: each waiting call gets a second row, with its call number in brackets. Its Result is worked out from the value returned to it, and then returned.
Example:Power(2, 4) works out 2 to the power 4. Its trace has 5 rows on the way down and 4 on the way back up. The answer is 16.
Call Function call N Result Return value
1 Power(2, 4) 4 2 * Power(2, 3)
2 Power(2, 3) 3 2 * Power(2, 2)
3 Power(2, 2) 2 2 * Power(2, 1)
4 Power(2, 1) 1 2 * Power(2, 0)
5 Power(2, 0) 0 1 1
(4) Power(2, 1) 1 2 * 1 2
(3) Power(2, 2) 2 2 * 2 4
(2) Power(2, 3) 3 2 * 4 8
(1) Power(2, 4) 4 2 * 8 16Two recursive calls: Fibonacci
Some recursive functions call themselves twice. Then the calls branch like a tree, and some work is repeated.
Some general cases make two recursive calls.
Fib(n) works out a number in the Fibonacci series. Each number in it is the sum of the two before it: Fib(n - 1) + Fib(n - 2).
- The first call runs to the end, with all of its own calls, before the second call starts.
- With two calls in each general case, the calls branch like a tree.
- The same values are worked out more than once:
Fib(4)makes 9 calls, 3 of themFib(1).
In the calls table, each call is indented under the call that made it.
Remember:Recursion is especially suited to problems that branch like this.
FUNCTION Fib(n : INTEGER) RETURNS INTEGER DECLARE Result : INTEGER IF n <= 1 THEN Result ← n ELSE Result ← Fib(n - 1) + Fib(n - 2) ENDIF RETURN Result ENDFUNCTION DECLARE Number : INTEGER INPUT Number OUTPUT Fib(Number)
Two base cases: a recursive binary search
A recursive binary search has two base cases, "not found" and "found". Each call searches only half of what is left.
A recursive function can have more than one base case. Search looks for Target between positions Low and High of a sorted list.
| Case | When | What it does |
|---|---|---|
| base case | Low > High: nothing is left to search | returns -1: not found |
| base case | the middle item is Target | returns that position |
| general case | otherwise | calls itself on the half that can hold Target: Mid + 1 to High, or Low to Mid - 1 |
Both base cases stop the recursion. Each call leaves fewer items to search, so one of the base cases is always reached.
Exam:Paper 4 has asked for this function in program code three times.
FUNCTION Search(Low : INTEGER, High : INTEGER, Target : INTEGER) RETURNS INTEGER DECLARE Mid : INTEGER IF Low > High THEN RETURN -1 // base case: not found ENDIF Mid ← (Low + High) DIV 2 IF List[Mid] = Target THEN RETURN Mid // base case: found ENDIF IF List[Mid] < Target THEN RETURN Search(Mid + 1, High, Target) ELSE RETURN Search(Low, Mid - 1, Target) ENDIF ENDFUNCTION
How the compiler makes recursion work
Each call gets its own stack frame on the call stack, so every recursive call keeps its own variables.
Every time a subroutine is called, the compiled code pushes a stack frame onto the call stack. A stack is like a pile of plates: the last one on is the first one off. The frame holds:
- the return address: where to carry on afterwards
- the parameters
- the local variables.
So every recursive call has its own copy of n, and no call overwrites another's.
When a call returns:
- its frame is popped
- the return address says where to continue
- the returned value is used by the call below it.
That is unwinding.
Watch out:If the base case is never reached, frames are pushed until the stack is full. This is a stack overflow.
1 FUNCTION Factorial(n : INTEGER) RETURNS INTEGER 2 IF n = 0 THEN 3 RETURN 1 4 ELSE 5 RETURN n * Factorial(n - 1) 6 ENDIF 7 ENDFUNCTION 8 9 DECLARE Answer : INTEGER 10 Answer ← Factorial(3) 11 OUTPUT Answer // the call stack at the base case, top first // Factorial n = 0 return to line 5 // Factorial n = 1 return to line 5 // Factorial n = 2 return to line 5 // Factorial n = 3 return to line 10
Recursion or iteration?
Recursion gives short, clear code for problems made of smaller copies of themselves, but it costs memory and time.
Most recursive algorithms can also be written with a loop. Paper 4 asks for both: a loop rewritten as recursion, or recursion rewritten as a loop.
Recursion is beneficial when a problem breaks down naturally into smaller versions of itself. Examples are a factorial, a mathematical series, or a tree, which branches. The recursive code is then short and close to the problem's own definition.
But recursion has costs:
- Memory: every call pushes a frame. Recursion n calls deep needs memory for n frames, while a loop reuses the same variables.
- Time: pushing and popping frames takes time.
- Size: the stack has a limited size, so very deep recursion overflows it.
FUNCTION FactLoop(n : INTEGER) RETURNS INTEGER DECLARE Answer : INTEGER DECLARE Count : INTEGER Answer ← 1 FOR Count ← 1 TO n Answer ← Answer * Count NEXT Count RETURN Answer ENDFUNCTION DECLARE Number : INTEGER INPUT Number OUTPUT FactLoop(Number)
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.What happens if a recursive function has no reachable base case?
2.Which of these is NOT one of the three essential features of recursion?
3.SumTo(n) returns n + SumTo(n - 2), and its base case is n = 0. What happens when SumTo(5) is called?
4.Inside the recursive FUNCTION Factorial, which line calls it again correctly in 9618 pseudocode?
5.In PROCEDURE Show(n), if n > 0 it outputs n and then calls Show(n - 1). If the OUTPUT is moved to after the recursive CALL, what does CALL Show(3) output?
6.Factorial(3) calls Factorial(2), which calls Factorial(1), which calls Factorial(0). Which call returns its value first?
7.What does each stack frame hold when a recursive subroutine is called?
8.When is recursion a good choice?
9.In an exam trace table for a recursive function, when is a waiting call's Result worked out?