A Level Computer Science · Chapter 21 · Component 02: Algorithms and programming
Large programs are built from small named pieces, subroutines, and some problems are solved most naturally by a subroutine that calls itself.
This chapter teaches how to write and use functions and procedures, how parameters pass data in and out, and how scope keeps variables apart. It then teaches recursion: how a subroutine calls itself, how the call stack makes it work, and when it is the right tool.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- write functions and procedures, and explain why programs are split into subroutines
- pass parameters by value and by reference, and predict the effect of each
- distinguish local and global variables, and explain why local variables are preferred
- write a recursive subroutine with a base case and a general case
- trace a recursive subroutine, showing the calls, the returns and the call stack
- compare recursion with iteration, and improve a recursive algorithm with memoisation
- explain stack overflow and calculate how deep a recursion can go
Time: three sessions, about 4 hours, plus the programming task.
You need first: sequence, selection and iteration from Programming constructs, and stacks from Arrays, records, stacks and queues.
The big picture
The big picture
A recipe for a cake might say "make the icing", with the icing recipe written out on another page. The main recipe stays short and readable. The icing recipe can be reused for other cakes, and if it is improved, every cake that uses it benefits. Programs work the same way.
A subroutine is a named block of code that does one job. The main program calls it by name, the subroutine runs, and then the program carries on where it left off. Splitting a program into subroutines makes it easier to write, test, read and change, and lets a team work on different parts at once.
Data flows into a subroutine through its parameters, and a function sends a result back with return. Variables created inside a subroutine are local: they exist only while it runs, so they cannot interfere with the rest of the program.
Some problems contain smaller copies of themselves. The factorial of 4 is 4 times the factorial of 3. A folder contains folders, which contain more folders. For these, a subroutine can call itself on the smaller problem. This is recursion, and it often turns a hard problem into a few short lines.
Recursion relies on the call stack. Every call gets its own stack frame, holding its parameters and local variables, so each copy of the subroutine keeps its own values. When a call finishes, its frame is popped and the call below it carries on.
The power of recursion comes with costs. Each frame uses memory, and a recursion that goes too deep overflows the stack. Some recursive algorithms repeat the same work many times over. Knowing when recursion helps, and how to make it efficient, is as important as knowing how to write it.
Subroutines and recursion also connect to the rest of the course. Every algorithm in the later chapters is written as a set of subroutines, and many of them, from merge sort to tree traversals, are recursive. Learning to read and trace them here pays off in every algorithm question.
Section 1
Functions and procedures
Why use subroutines?
A subroutine is a named, self-contained block of code that carries out one task. Breaking a program into subroutines is called modular programming. Each subroutine can be written and tested on its own, then trusted when it is used.
Subroutines avoid repetition. Code that would otherwise appear five times appears once, and is called five times. A bug fixed in the subroutine is fixed everywhere. Well-named subroutines also make the main program read almost like a description of what it does.
Subroutines also hide detail. Once area(width, height) is written and tested, the rest of the program only needs to know what it does, not how. This is abstraction, and it is how large systems stay manageable. A programmer working on the main program can treat each subroutine as a single trusted step.
Libraries take the idea further. A library is a collection of tested subroutines that many programs can share, such as Python's math module. Calling math.sqrt(2) uses code written and checked by someone else, which saves time and avoids reinventing well-known algorithms.
Functions and procedures
A function returns a value to the code that called it, so a call to a function can be used inside an expression. A procedure carries out a task but returns no value. In Python, both are written with def; a function contains a return statement with a value.
function area(width, height)
return width * height
endfunction
procedure showArea(width, height)
print("Area: " + str(area(width, height)))
endprocedure
Common mistake: thinking a procedure returns a value. A procedure carries out its task, such as printing, and then finishes. It sends nothing back, so x = showArea(3, 4) stores no useful value. Use a function whenever the caller needs a result.
A function should usually do one job and avoid side effects, such as printing or changing global variables. A function whose result depends only on its parameters is easy to test: the same arguments always give the same result. Printing and other output are better left to procedures, or to the main program.
Subroutine names matter. A good name is a verb or a short phrase that says what the subroutine does, such as calculateTotal or isValidPostcode. A function that returns a Boolean often starts with is or has, so that a condition such as if isValidPostcode(code) reads naturally.
Worked example 1: calling a function
Using the function area above, find the value of area(3, 4) + area(2, 5).
| Working | Reason |
|---|---|
| area(3, 4) runs with width 3 and height 4, returning 12 | The arguments are matched to the parameters in order |
| area(2, 5) runs separately, returning 10 | Each call is independent of the last |
| 12 + 10 = 22 | The returned values are used in the expression |
| The whole expression has the value 22 | A function call stands for its result |
The call stack for subroutines
When one subroutine calls another, the computer must remember where to come back to. Each call pushes a frame onto the call stack, holding the return address, the parameters and the local variables. When the subroutine returns, its frame is popped.
Worked example 2: a function inside a function
A function square(n) returns n × n. Find square(square(3)).
| Working | Reason |
|---|---|
| The inner call square(3) runs first, returning 9 | An argument is worked out before the call |
| The outer call becomes square(9) | The result of the inner call is passed on |
| square(9) returns 81 | It multiplies 9 by itself |
| square(square(3)) = 81, which is 3 to the power 4 | Squaring twice raises to the fourth power |
Designing with subroutines
Top-down design breaks a problem into a few large tasks, then breaks each task into smaller ones, until every piece is small enough to write as one subroutine. The result is a hierarchy chart, with the main program at the top and the simplest subroutines at the bottom.
Each subroutine can then be built and tested separately, often by different people. An interface, which is the subroutine's name, its parameters and what it returns, is agreed first. As long as each subroutine keeps to its interface, the pieces fit together when they are combined.
Built-in and user-defined subroutines
Every language comes with built-in subroutines, such as print, input, len and int in Python. They are called in exactly the same way as subroutines you write yourself. Knowing what a built-in function returns, and its type, matters. Input always returns a string, so a number typed by the user must be cast with int before any arithmetic.
User-defined subroutines are the ones the programmer writes. A program is easier to follow when its own subroutines behave like the built-in ones: clear names, a fixed set of parameters, and a single, predictable result.
Check yourself. Why should a subroutine that calculates a VAT amount be a function rather than a procedure?
Show the answer
The calling code needs the VAT amount back to use it, for example to add it to a price. A function returns a value, while a procedure does not, so a function is the right choice.
Section 2
Parameters
Parameters and arguments
A parameter is a variable named in a subroutine's definition, such as width. An argument is the actual value passed in a call, such as 3. When the subroutine is called, each argument is copied into or linked to its parameter, in the order they are written.
Parameters make subroutines general. Instead of one function for a 3 by 4 rectangle and another for 2 by 5, a single area(width, height) works for any rectangle. A subroutine with parameters depends only on what it is given, which makes it easy to test.
Passing by value
When a parameter is passed by value, the subroutine receives a copy of the argument. Changes to the parameter inside the subroutine affect only the copy. The caller's variable keeps its original value. This is the safe default, because a subroutine cannot accidentally change its caller's data.
Common mistake: thinking a value parameter changes the caller's variable. A parameter passed by value is a copy. However the subroutine changes it, the caller's variable is untouched once the call ends. Only a parameter passed by reference can change the caller's data.
Worked example 3: passing by value
total is 5. A procedure addOn(x) does x = x + 3 and prints x. It is called as addOn(total), with x passed by value. Give what is printed and the value of total afterwards.
| Working | Reason |
|---|---|
| x receives a copy of total, so x = 5 | Passing by value copies the argument |
| x = x + 3 makes x equal 8, which is printed | Only the copy changes |
| When the procedure ends, x is discarded | The copy was local to the procedure |
| total is still 5 after the call | The caller's variable was never touched |
Passing by reference
When a parameter is passed by reference, the subroutine receives the address of the caller's variable. The parameter and the argument are then the same storage, so any change made inside the subroutine is a change to the caller's variable. In exam pseudocode this is written with byRef, and byVal marks a value parameter.
Passing by reference is useful when a subroutine must change several of the caller's variables, such as a procedure that swaps two values. It also avoids copying large data, such as a big array. The risk is that a subroutine can change data its caller did not expect to change.
Worked example 4: passing by reference
Repeat worked example 3 with x passed by reference.
| Working | Reason |
|---|---|
| x refers to total itself, which holds 5 | Passing by reference shares the variable |
| x = x + 3 changes total to 8, and 8 is printed | x and total are the same storage |
| When the procedure ends, the link to total is removed | The reference was local to the procedure |
| total is now 8 after the call | The change was made to the caller's variable |
Arrays and objects as parameters
Many languages treat large data differently. In Python, a list passed to a function is not copied: the function receives a reference to the same list. If the function appends to the list or changes an element, the caller sees the change, even though the parameter looks like an ordinary one.
That saves time, because copying a list of a million items would be slow. It also means a function can change a caller's data by surprise. When a function must not change a list, it can work on a copy, made with list(items) or items.copy().
The two terms are about what the subroutine receives, not about what it does with it. A by-value parameter can be changed freely inside the subroutine; the change simply stays local. A by-reference parameter that is never changed behaves exactly like a value parameter, but without the cost of a copy.
Default and optional parameters
Some languages let a parameter have a default value, used when the caller leaves it out. In Python, def greet(name, greeting="Hello") can be called as greet("Asha") or as greet("Asha", "Hi"). Defaults keep common calls short while still allowing the unusual case.
The number and order of arguments must match the parameters, unless defaults or named arguments are used. Calling area(3) when area needs two parameters is an error. Calling area(4, 3) instead of area(3, 4) silently swaps the arguments, which matters whenever their order is significant.
Exam pseudocode assumes parameters are passed by value unless byRef is written. In Python, numbers and strings behave as if passed by value, because they cannot be changed in place, while lists and objects can be changed through the parameter.
Check yourself. A procedure swap(a, b) exchanges its two parameters. Why must they be passed by reference?
Show the answer
Passed by value, swap would exchange only its own copies, and the caller's variables would be unchanged when it finished. Passed by reference, a and b are the caller's variables, so the exchange is seen after the call.
Section 3
Scope
Local and global variables
The scope of a variable is the part of the program where it can be used. A local variable is declared inside a subroutine. It exists only while that subroutine runs, and it cannot be seen from outside. A global variable is declared in the main program and can be used anywhere.
Two subroutines can each have a local variable with the same name, and they are completely separate. A local variable can even share a name with a global one. Inside the subroutine, the local variable hides the global, which is untouched.
Common mistake: assuming a local variable changes the global of the same name. If a subroutine declares its own count, setting count = 3 inside it changes only the local count. The global count keeps its value. In Python, a function must declare global count to change the global one.
Worked example 5: local and global
A global count is set to 10. A function tally creates a local count, sets it to 3 and returns count × 2. The main program prints tally() then count. What is printed?
| Working | Reason |
|---|---|
| Inside tally, count refers to the local variable | A local name hides the global one |
| The local count is 3, so tally returns 6 | The local value is doubled |
| The local count is discarded when tally ends | Local variables exist only during the call |
| The program prints 6, then the global count, 10 | The global was never changed |
Why prefer local variables?
Local variables make subroutines self-contained. A subroutine that uses only its parameters and locals can be understood, tested and reused on its own, because nothing outside can change its data unexpectedly. Its memory is also freed when it returns.
Global variables are visible everywhere, so any part of the program might change them. When a global has the wrong value, every subroutine is a suspect, which makes bugs hard to find. Globals do have a place, for values that are truly shared, such as a constant for the tax rate.
Scope and the call stack
Local variables live in the subroutine's stack frame. When the subroutine is called, its frame is pushed, creating fresh local variables. When it returns, the frame is popped and the locals disappear. That is why a local variable does not keep its value from one call to the next.
It is also why recursion works. Each recursive call pushes its own frame, so each call has its own copy of n and of every other local. The call fact(3) and the call fact(2) never share an n, even though they run the same code.
Some languages also have block scope, where a variable declared inside a loop or an IF exists only within that block. Python does not: a variable created inside a loop is still visible after the loop ends, as long as it is in the same function.
Constants and shared data
Values that every part of a program needs, but that never change, are best held as global constants. A constant such as MAX_PLAYERS = 4 cannot be changed by mistake, so it has none of the risks of a global variable. Writing constants in capital letters makes them easy to spot.
Data that does change, but is needed in many subroutines, is usually better passed as a parameter or kept inside an object. Object-oriented programming, in the next chapter, bundles data together with the subroutines that are allowed to change it, which solves the problem that global variables create.
Testing subroutines
Because a subroutine with only parameters and locals depends on nothing else, it can be tested on its own, before the rest of the program exists. A small test program calls it with chosen arguments and checks each result. This is unit testing, and it catches errors while they are still easy to find.
Check yourself. Give one advantage and one disadvantage of using a global variable to hold a running total.
Show the answer
An advantage is that every subroutine can reach the total without it being passed as a parameter. A disadvantage is that any subroutine can change it by mistake, which makes errors hard to trace.
Section 4
Recursion
A subroutine that calls itself
A recursive subroutine is one that calls itself. Every recursive subroutine needs two parts. The base case is a simple version of the problem that is answered directly, without another call. The general case breaks the problem into a smaller one and calls the subroutine on it.
function fact(n)
if n <= 1 then
return 1
else
return n * fact(n - 1)
endif
endfunction
Each call works on a smaller n, so the calls must eventually reach the base case. Then the answers are passed back up, each call multiplying by its own n. The base case is what makes the recursion stop.
Common mistake: writing a recursive function with no base case. Without a base case, the function calls itself for ever, with smaller and smaller arguments. Each call pushes a new frame, until the call stack runs out of space and the program crashes with a stack overflow.
Worked example 6: tracing a recursive function
Trace fact(4), giving the calls in order and the value each call returns.
| Working | Reason |
|---|---|
| fact(4) calls fact(3), which calls fact(2), which calls fact(1) | Each general case calls on a smaller n |
| fact(1) returns 1 without another call | n <= 1 is the base case |
| fact(2) returns 2 × 1 = 2, then fact(3) returns 3 × 2 = 6 | Each call uses the value returned to it |
| fact(4) returns 4 × 6 = 24 | The last call to finish was the first made |
Figure 21.1 shows the call stack while fact(n) runs. Step through the calls and the returns, and change n. Then switch on the wrong model, which removes the base case.
The call stack for factorial(n)
- Frames on the stack
- 4
- Deepest the stack gets
- 4
- Final result
- not yet
Worked example 7: recursion over a list
A function sum(list) returns 0 for an empty list, and otherwise the first item plus sum of the rest. Find sum([4, 7, 1]) and the depth of the call stack.
| Working | Reason |
|---|---|
| sum([4, 7, 1]) = 4 + sum([7, 1]) | The general case splits off the first item |
| sum([7, 1]) = 7 + sum([1]) = 7 + 1 + sum([]) | Each call works on a shorter list |
| sum([]) = 0, so the totals return 1, 8, then 12 | The empty list is the base case |
| Result 12, with 4 frames at the deepest point | One frame per call, including the empty list |
Writing a recursive subroutine
A reliable way to write a recursive subroutine has three steps. First, find the simplest case and write down its answer: that is the base case. Next, assume the subroutine already works for a smaller input. Finally, use that smaller answer to build the answer for the full input: that is the general case.
For the sum of a list, the simplest case is an empty list, whose sum is 0. If sum already works on the rest of the list, the full sum is the first item plus the sum of the rest. That reasoning is all the recursive function needs.
The step that feels like a leap of faith is the assumption that the smaller call works. It is justified because the calls get smaller each time and must reach the base case, which is certainly correct. Each step back up is then correct too.
How recursion uses the call stack
When fact(4) is called, a frame for it is pushed, holding n = 4. It reaches the call fact(3), so a second frame is pushed above it, with its own n = 3. The first frame is paused, waiting for the answer. This repeats until fact(1) is on top.
fact(1) returns 1 at once, and its frame is popped. The frame for fact(2) is now on top again, and it carries on from where it paused, working out 2 × 1. Each frame in turn resumes, finishes and is popped, until only the original call is left to return the final answer.
Check yourself. A recursive function count(n) returns 0 when n is 0, and otherwise 1 + count(n − 1). What is count(5), and what is the base case?
Show the answer
count(5) = 1 + count(4), and so on down to count(0) = 0, so it adds 1 five times and returns 5. The base case is n = 0, which returns 0 without another call.
Section 5
Tracing recursion
Work done on the way down or on the way up
A recursive subroutine can do work before its recursive call, or after it. Work before the call happens on the way down, in the order the calls are made. Work after the call happens on the way up, in the reverse order, as each call returns.
procedure down(n)
if n > 0 then
print(n)
down(n - 1)
endif
endprocedure
procedure up(n)
if n > 0 then
up(n - 1)
print(n)
endif
endprocedure
Exam questions often ask for the output of a short recursive procedure like these. The safest method is to write every call, indented, and to write each print exactly where it happens: before the indented call or after it returns.
Worked example 8: before or after the call
Give the output of down(3) and of up(3).
| Working | Reason |
|---|---|
| down(3) prints 3, then calls down(2) | The print comes before the call |
| down prints 3, 2, 1 in that order | Each call prints on the way down |
| up(3) calls up(2) before printing, and so on to up(0) | The print waits until the call returns |
| up prints 1, 2, 3, because up(1) finishes first | The prints happen on the way back up |
Common mistake: reading the output in the order the calls are made. When a recursive procedure prints after its recursive call, the deepest call prints first. Tracing the calls downwards and writing the output in that order gives it backwards. Follow each return to see when the output happens.
Some recursive subroutines do work both before and after the call. A procedure that prints n, calls itself, then prints n again would print 3, 2, 1 on the way down and 1, 2, 3 on the way up. Tracing it means following both halves of every call.
Calls that branch
Some recursive subroutines call themselves more than once. The Fibonacci numbers are defined by fib(0) = 0, fib(1) = 1, and fib(n) = fib(n − 1) + fib(n − 2). A direct recursive version makes two calls each time, so its calls form a tree.
Common mistake: thinking each Fibonacci value is worked out only once. The direct recursive version has no memory of earlier answers. Both fib(4) and fib(3) work out fib(2) for themselves, and so on down the tree. So the number of calls grows exponentially, not in step with n.
Worked example 9: counting the calls
Find fib(5) and the total number of calls the direct recursive version makes.
| Working | Reason |
|---|---|
| fib(5) = fib(4) + fib(3) = 3 + 2 = 5 | Each value is the sum of the two before |
| Count the calls: C(n) = C(n − 1) + C(n − 2) + 1 | Each call makes two smaller calls, plus itself |
| C(0) = C(1) = 1, then C(2) = 3, C(3) = 5, C(4) = 9 | Build the counts from the bottom up |
| C(5) = 9 + 5 + 1 = 15 calls | Fifteen calls for one small answer |
Derivation: the number of calls made by recursive Fibonacci
Each call to fib(n), for n of 2 or more, makes one call to fib(n − 1) and one to fib(n − 2). So the count of calls obeys its own recurrence.
Adding 1 to both sides turns this into the Fibonacci rule itself, for the quantity C(n) + 1. Checking the first values pins it down.
For n = 5, fib(6) = 8, so C(5) = 15. For n = 10, fib(11) = 89, so C(10) = 177. The calls grow in step with the Fibonacci numbers themselves, which is exponential.
Tracing a branching recursion by hand is easiest with a call tree. Write the first call at the top, draw a branch to each call it makes, and repeat until every branch ends in a base case. Then work back up, writing each call's value beside it. The number of nodes in the tree is the number of calls.
The Towers of Hanoi
The Towers of Hanoi is a puzzle with n discs on peg A, which must be moved to peg C. Only one disc moves at a time, and a larger disc may never sit on a smaller one. The recursive solution moves n − 1 discs out of the way, moves the largest disc, then moves the n − 1 discs back on top.
Worked example 10: Towers of Hanoi
Give the moves for 3 discs, and the number of moves needed for 10 discs.
| Working | Reason |
|---|---|
| Move 2 discs from A to B, using C: A→C, A→B, C→B | Clear the two smaller discs out of the way |
| Move the largest disc: A→C | It moves exactly once |
| Move 2 discs from B to C, using A: B→A, B→C, A→C | Put the smaller discs back on top |
| 7 moves for 3 discs; for 10 discs, 2¹⁰ − 1 = 1,023 moves | The number of moves doubles, plus one |
Derivation: the number of moves for the Towers of Hanoi
Moving n discs means moving n − 1 discs twice, plus one move for the largest disc. Write M(n) for the number of moves.
Adding 1 to both sides shows that M(n) + 1 doubles each time a disc is added. Starting from M(1) + 1 = 2 gives a power of 2.
Three discs need 2³ − 1 = 7 moves, and 64 discs would need about 1.8 × 10¹⁹. The recursive solution is short, but the work it describes is exponential.
The Towers of Hanoi shows recursion at its most elegant. The whole solution is three lines: move n − 1 discs out of the way, move the largest, move n − 1 discs back. Writing the same solution with loops is possible, but much harder to see and to get right.
Recursion also explains how many puzzles and games are solved by computer. A program that plays noughts and crosses can try a move, then call itself to play the rest of the game from the new position. When that call returns with a result, it undoes the move and tries the next one. This pattern is called backtracking.
Check yourself. Using the formula, how many moves are needed for 5 discs?
Show the answer
The formula gives 2⁵ − 1 = 32 − 1 = 31 moves. Check it against the recurrence: M(4) = 15, so M(5) = 2 × 15 + 1 = 31.
Section 6
Recursion and efficiency
Recursion against iteration
Any recursive algorithm can be rewritten with a loop, and any loop can be rewritten recursively. A recursive version is often shorter and closer to the way the problem is described, especially for trees, nested data and divide-and-conquer algorithms such as merge sort.
An iterative version is usually faster and uses less memory. A loop reuses the same variables, while recursion pushes a frame for every call that has not yet returned. For a simple task such as a factorial, a loop is the better choice in practice.
Common mistake: thinking recursion is always faster than iteration. Recursion is often shorter to write, but every call costs time and stack memory. A loop that does the same job is usually faster and cannot overflow the stack. Choose recursion for clarity, not for speed.
Recursion does have practical strengths. Algorithms on trees and nested data are far shorter when written recursively. Divide-and-conquer algorithms, such as merge sort and quick sort, split a problem into halves and solve each half the same way, which is naturally recursive. Many languages, especially functional ones, rely on recursion instead of loops.
Some compilers can turn certain recursive calls into loops automatically. If the recursive call is the very last thing a function does, called tail recursion, the frame can be reused. Python does not do this, which is one reason deep recursion in Python fails early.
Memoisation
The recursive Fibonacci function is slow because it works out the same values again and again. Memoisation fixes this: the first time a value is worked out, it is stored, and later calls look it up instead of recomputing it. Each value is then calculated only once.
Figure 21.2 counts the calls made to work out fib(n), with and without memoisation. Move n and compare the two lines. Then switch on the wrong model, which assumes each value is only worked out once.
Calls made by recursive Fibonacci
- fib(6)
- 8
- Calls, plain recursion
- 25
- Calls, memoised
- 11
Worked example 11: the effect of memoisation
Compare the calls made to work out fib(10) by the direct recursion and by the memoised version.
| Working | Reason |
|---|---|
| Direct recursion: 2 × fib(11) − 1 = 2 × 89 − 1 = 177 calls | The formula from the derivation |
| Memoised: each of fib(0) to fib(10) is worked out once | Stored values are looked up afterwards |
| Counting each lookup as a call too gives 19 calls | Most values are found in the store |
| 177 calls fall to 19, and the gap widens as n grows | Memoisation turns exponential into linear growth |
Making the problem smaller faster
The speed of a recursion depends on how quickly it shrinks the problem. Raising x to the power n by x × x^(n − 1) makes n + 1 calls. Halving instead, with x^n = (x^(n DIV 2))², shrinks n by half each time, so the calls grow only as log n.
Worked example 12: two ways to raise to a power
Count the calls made to work out 2¹⁰ by the simple recursion and by repeated halving.
| Working | Reason |
|---|---|
| Simple: power(10) calls power(9), down to power(0): 11 calls | n goes down by 1 each time |
| Halving: power(10) calls power(5), then power(2) | n DIV 2 halves the problem |
| Then power(1) and power(0): 5 calls in all | Roughly log₂ n plus two calls |
| Both give 1,024, but halving needs 5 calls instead of 11 | Shrinking faster saves calls |
Halving is the idea behind binary search and merge sort as well. Whenever a recursive algorithm can split its problem in half, rather than shaving off one item at a time, its depth falls from n to about log₂ n. That is the difference between a million calls and twenty.
Stack overflow
Each recursive call uses a frame of stack memory, and the stack has a fixed size. If a recursion goes deeper than the stack can hold, the program crashes with a stack overflow. That happens with a missing base case, and also with a correct recursion on a very large input.
Worked example 13: how deep can a recursion go?
Each frame of a recursive function uses 64 bytes, and 8,192 bytes are set aside for the stack. How deep can the recursion go?
| Working | Reason |
|---|---|
| Frames that fit = 8192 ÷ 64 | Each frame takes the same space |
| 8192 ÷ 64 = 128 frames | The stack holds at most 128 calls |
| fact(100) needs 100 frames, so it fits | It stays below the limit of 128 |
| fact(200) would need 200 frames and overflow | The stack runs out after 128 frames |
Python sets a recursion limit, 1,000 calls by default, and raises a RecursionError if a recursion goes deeper. The limit protects the program from crashing in a less controlled way. It can be raised, but a recursion that needs it raised is usually better rewritten as a loop.
Choosing between recursion and iteration is a judgement. Recursion suits problems with a recursive structure and modest depth. Iteration suits simple repetition, very deep problems, and code that must be as fast as possible. Memoisation can rescue a recursive design that repeats work.
Memoisation is one example of a wider idea, dynamic programming. A dynamic programming algorithm solves each small problem only once and stores the answer. It then builds larger answers from the stored ones, instead of solving the same small problems again and again. A loop that fills a table of Fibonacci values from the bottom up is the same idea without recursion at all.
Check yourself. Why does a loop that works out a factorial never cause a stack overflow?
Show the answer
A loop reuses the same variables on every pass and makes no new calls. It pushes no frames, so its memory use does not grow with n, and the stack can never fill up.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Function | Subroutine that returns a value | area(3, 4) returns 12 | Can be used inside an expression |
| Procedure | Subroutine that returns nothing | showArea(3, 4) prints | Called as a statement |
| By value | The subroutine gets a copy | total stays 5 | The caller's variable cannot change |
| By reference | The subroutine shares the variable | total becomes 8 | Use when the caller's data must change |
| Local variable | Exists only inside its subroutine | count inside tally | Hides a global of the same name |
| Global variable | Visible to the whole program | A tax-rate constant | Easy to change by mistake |
| Recursion | A subroutine that calls itself | fact(n) = n × fact(n − 1) | Needs a base case and a general case |
| Call stack | A frame for every active call | fact(4) is 4 frames deep | Too deep causes stack overflow |
| Memoisation | Store results to avoid recomputing | fib(10) in 19 calls | Exponential becomes linear |
| Towers of Hanoi | Classic recursive puzzle | 3 discs in 7 moves | 2ⁿ − 1 moves |
Programming task
Programming task: counting recursive calls
Aim
Write a Python program that works out Fibonacci numbers by direct recursion and by memoisation, and counts the calls each makes. The counts must match the formula 2 × fib(n + 1) − 1, and the memoised version must give the same values far faster.
Design
A global counter is reset before each run and increased by 1 at the start of every call. The direct function follows the definition exactly. The memoised function keeps a dictionary of values already worked out, and returns a stored value straight away when it can.
A third, iterative function works out the same values with a loop, as a check that the recursive answers are right. Comparing all three on the same inputs tests both the values and the call counts.
Code
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
def fib_memo(n, memo):
global calls
calls += 1
if n in memo:
return memo[n]
value = n if n < 2 else fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
memo[n] = value
return value
def fib_loop(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
for n in [5, 10, 20]:
calls = 0
value = fib(n)
direct = calls
calls = 0
fib_memo(n, {})
print(n, value, fib_loop(n), direct, calls)
The global counter is the one place where a global variable is the simple choice, because every call must add to the same total. The memo dictionary is passed as a parameter, so each run starts with an empty store.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | fib(5) | 5, with 15 calls | Matches worked example 9 |
| 2 | fib(10) | 55, with 177 calls | Matches the formula 2 × 89 − 1 |
| 3 | fib_memo(10, {}) | 55, with 19 calls | Memoisation cuts the calls |
| 4 | fib(0) and fib(1) | 0 and 1, with 1 call each | The base cases |
| 5 | fib_loop(20) | 6765 | The loop checks the recursive values |
| 6 | fib(20) | 6765, with 21,891 calls | Shows the exponential growth |
| 7 | fib_memo(20, {}) | 6765, with 39 calls | Grows linearly, as 2n − 1 |
Evaluation
Every value agrees across the three methods, and the call counts match the formula exactly. Tests 6 and 7 show the point of the task: 21,891 calls against 39 for the same answer.
An improvement would time each method as well as counting calls. Another would try fib(2000) to show that the memoised version still overflows the stack eventually, while the loop does not.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State two differences between a function and a procedure.
Worked solution to Q1
A function returns a value to the code that called it, while a procedure does not. So a function call can be used inside an expression, such as total = price + vat(price), while a procedure is called as a statement on its own.
Q2. Name the two parts every recursive subroutine needs, and say what each does.
Worked solution to Q2
The base case answers a simple version of the problem directly, without another call, so the recursion stops. The general case calls the subroutine on a smaller version of the problem and uses the result.
Q3. Describe what is stored in a stack frame when a subroutine is called.
Worked solution to Q3
A stack frame holds the return address, so the program knows where to continue afterwards. It also holds the subroutine's parameters and its local variables, so each call keeps its own values.
Rung 2: Application
Q4. A function triple(n) returns 3 × n. Find triple(triple(4)) + triple(2).
Worked solution to Q4
The inner call triple(4) returns 12, so triple(triple(4)) is triple(12), which returns 36. Then triple(2) returns 6. Adding the two results gives 36 + 6 = 42.
Q5. score is 10. A procedure bonus(s) does s = s + 5. State score after bonus(score) if s is passed by value, and if it is passed by reference.
Worked solution to Q5
By value, s is a copy, so only the copy becomes 15 and score is still 10 afterwards. By reference, s is score itself, so the change is made to score, which becomes 15.
Q6. Trace fact(5) and give its value.
Worked solution to Q6
The calls go down from fact(5) to fact(1), which returns 1. Then the returns come back up: fact(2) = 2, fact(3) = 6, fact(4) = 24 and fact(5) = 5 × 24 = 120.
Q7. Give the output of up(4), where up prints n after its recursive call.
Worked solution to Q7
up(4) calls up(3), which calls up(2), and so on down to up(0), which does nothing. Each call then prints as it returns, starting with the deepest, so the output is 1, 2, 3, 4.
Rung 3: Analysis
Q8. Use the formula C(n) = 2 × fib(n + 1) − 1 to find how many calls direct recursion makes for fib(8), given fib(9) = 34.
Worked solution to Q8
The formula gives C(8) = 2 × fib(9) − 1 = 2 × 34 − 1 = 67 calls. A memoised version would need only 2 × 8 − 1 = 15, because each value is worked out once.
Q9. A function countdown(n) prints n, then calls countdown(n − 1), with no base case. Explain what happens when countdown(3) runs.
Worked solution to Q9
It prints 3, 2, 1, 0, −1 and carries on into negative numbers, because nothing stops the calls. Each call pushes a frame, so the stack eventually fills and the program crashes with a stack overflow.
Q10. Each frame of a recursive search uses 48 bytes, and the stack holds 12,000 bytes. Find the deepest recursion possible.
Worked solution to Q10
The number of frames that fit is 12,000 ÷ 48 = 250. So the recursion can go at most 250 calls deep before the stack overflows. A search needing more levels must be rewritten as a loop.
Q11. Explain why a global variable called total and a local variable called total in a function do not interfere.
Worked solution to Q11
The local total exists only inside the function, in that call's stack frame. Inside the function, its name hides the global one. Changes to the local total never reach the global, which keeps its value.
Rung 4: Stretch
Q12. Apply the Towers of Hanoi formula to find the number of moves for 64 discs, to 2 significant figures.
Worked solution to Q12
The formula is 2⁶⁴ − 1 moves. Since 2¹⁰ is about 10³, 2⁶⁴ = 2⁴ × 2⁶⁰ is about 16 × 10¹⁸. More precisely it is 1.8 × 10¹⁹ moves, to 2 significant figures.
Q13. Rewrite fact(n) as an iterative function, and explain one advantage of the iterative version.
Worked solution to Q13
Set result = 1, then for i = 2 to n, set result = result × i, and return result. The loop reuses one set of variables, so it uses a fixed amount of memory and can never overflow the stack.
Q14. Count the calls made by the halving method to work out 3²⁰.
Worked solution to Q14
The exponent halves each call: power(20) calls power(10), then power(5), power(2), power(1) and power(0). That is 6 calls in all, compared with 21 for the simple recursion.
Exam practice
Exam technique and worked answer workshop
To trace a recursive subroutine, write each call on a new line, indented one step further than the call that made it. When a call returns, write its value beside it. Then follow the returns back up, using each value in the line above. Examiners give marks for the calls and for the returns.
When asked to write a recursive subroutine, write the base case first. Then write the general case, and check that it really makes the problem smaller. A missing or unreachable base case is the commonest error, and it loses most of the marks.
For parameter questions, say clearly whether the parameter is a copy or the caller's own variable, and give the caller's value after the call. The words by value and by reference must be used accurately.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
(a) Give two differences between a function and a procedure. [2]
(b) Explain the difference between a local and a global variable. [2]
Mark scheme for exam question 1
- B1 a function returns a value; a procedure does not
- B1 a function call can be used in an expression; a procedure is called as a statement
- B1 a local variable exists only inside the subroutine that declares it, while the subroutine runs
- B1 a global variable can be used anywhere in the program, for its whole run
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
total is 5. A procedure addOn(x) does x = x + 3 and prints x. It is called as addOn(total).
(a) State what is printed and the value of total afterwards if x is passed by value. [2]
(b) State the value of total afterwards if x is passed by reference. [1]
(c) Explain the difference in the results. [2]
Mark scheme for exam question 2
- B1 8 is printed
- B1 total is still 5 by value
- B1 total is 8 by reference
- B1 by value, x is a copy of total, so only the copy changes
- B1 by reference, x refers to total itself, so the change is made to total
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
A function fact(n) returns 1 if n <= 1, and otherwise n × fact(n − 1). Trace fact(4), showing every call and the value each call returns.
Mark scheme for exam question 3
- B1 calls fact(4), fact(3), fact(2), fact(1) in that order
- B1 fact(1) returns 1 as the base case
- B1 fact(2) returns 2
- B1 fact(3) returns 6
- B1 fact(4) returns 24
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
fib(n) returns n if n < 2, and otherwise fib(n − 1) + fib(n − 2).
(a) State the value of fib(5). [1]
(b) Calculate the number of calls made to work out fib(5). [2]
(c) Explain why the function is inefficient, and how memoisation improves it. [2]
Mark scheme for exam question 4
- B1 fib(5) = 5
- M1 calls counted with C(n) = C(n − 1) + C(n − 2) + 1, or from a call tree
- A1 15 calls
- B1 the same values, such as fib(3) and fib(2), are worked out many times
- B1 memoisation stores each value the first time, so later calls look it up instead
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A program must total the sizes of every file in a folder, where folders can contain other folders to any depth. Discuss whether the program should use recursion or iteration.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of both approaches applied to nested folders, covering clarity, memory and the risk of stack overflow. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct description of recursion and iteration with some reference to the folders. The comparison or the conclusion is limited.
Level 1 (1–2 marks): some relevant points, such as that recursion calls itself, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- folders contain folders, so the problem contains smaller copies of itself
- a recursive function totals a folder by calling itself on each subfolder
- the base case is a folder with no subfolders, or a single file
- the recursive version is short and mirrors the structure of the data
- each call pushes a stack frame, so very deep nesting could cause a stack overflow
- an iterative version needs an explicit stack or queue of folders still to visit
- the iterative version uses memory more predictably and cannot overflow the call stack
- folder nesting is rarely very deep, so recursion is a reasonable, clear choice
Annotated model answer: exam question 5
"Folders contain folders to any depth, so the problem contains smaller copies of itself. A recursive function can total a folder by adding the sizes of its files to the totals of its subfolders, calling itself on each one. The base case is a folder with no subfolders." (Recursion applied, with a base case.)
"The recursive version is short and mirrors the structure of the folders, so it is easy to read and check." (Advantage, linked to the data.)
"Each call pushes a frame onto the call stack. If folders were nested very deeply, the stack could overflow. An iterative version avoids this by keeping its own stack of folders still to visit, using a loop." (Disadvantage and the iterative alternative.)
"Real folder trees are rarely more than a few dozen levels deep, so stack overflow is unlikely. I would use recursion here, because its clarity outweighs the small risk." (A justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It compares both approaches for this problem and justifies its choice.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
Write a recursive function power(x, n) that returns x to the power n, for a whole number n of 0 or more.
Mark scheme for exam question 6
- B1 a function header taking x and n
- B1 a base case for n = 0
- B1 which returns 1
- B1 the general case calls power with n − 1
- M1 multiplies the result of the call by x
- A1 returns the result, with the function ended correctly
Annotated model answer: exam question 6
function power(x, n)
if n == 0 then
return 1
else
return x * power(x, n - 1)
endif
endfunction
The header earns the first mark. The test for n == 0 and its return of 1 earn the next two, because x to the power 0 is 1. The call on n − 1 earns the fourth mark, multiplying by x earns the method mark, and returning the result earns the last.
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) State what is stored on the call stack when a subroutine is called. [2]
(b) Each stack frame of a recursive function uses 64 bytes, and the stack has 8,192 bytes. Calculate the deepest the recursion can go. [2]
Mark scheme for exam question 7
- B1 the return address
- B1 the parameters and local variables
- M1 8192 ÷ 64
- A1 128 frames
Exam question 8 (5 marks · Paper 02 · about 7 minutes)
The Towers of Hanoi moves n discs from peg A to peg C.
(a) State the number of moves needed for 3 discs. [1]
(b) Give the first three moves for 3 discs. [2]
(c) Calculate the number of moves needed for 10 discs. [2]
Mark scheme for exam question 8
- B1 7 moves
- B1 A→C, then A→B
- B1 then C→B
- M1 2¹⁰ − 1
- A1 1,023 moves
Connections
Synoptic link
Recursion runs through the rest of the course. Searching and sorting algorithms uses it in merge sort and quick sort, and in a recursive binary search. Linked lists, hash tables, graphs and trees uses it for tree traversals, where each subtree is a smaller tree.
The call stack is the stack from Arrays, records, stacks and queues, and its stack pointer is a register described in Processor architecture and performance. Algorithm analysis and Big O notation explains why 2ⁿ − 1 moves make the Towers of Hanoi intractable for large n.
Synoptic question 1. A recursive binary search halves a sorted list of 1,000,000 items on each call. Roughly how many frames deep does it go?
Answer to synoptic question 1
Each call halves the list, so the depth is about log₂ 1,000,000. Since 2²⁰ is about 1,048,576, the search goes about 20 frames deep. That is tiny, so a recursive binary search is safe even for huge lists.
Recap
Recap and next step
- Subroutines split a program into named, testable pieces; a function returns a value and a procedure does not.
- A parameter passed by value is a copy, so the caller's variable is unchanged; passed by reference, it is the caller's variable.
- Local variables exist only inside their subroutine and hide globals of the same name; locals make subroutines self-contained.
- A recursive subroutine needs a base case and a general case that makes the problem smaller; each call has its own stack frame.
- Work done after the recursive call happens in reverse order; branching recursion such as Fibonacci repeats work, and Hanoi needs 2ⁿ − 1 moves.
- Memoisation stores results to avoid recomputing; recursion that goes too deep causes a stack overflow, which a loop avoids.
Next chapter: Object-oriented programming groups data and the subroutines that act on it into classes and objects.
For your exam board
OCR A Level Computer Science (H446): this chapter covers recursion, global and local variables, modularity, functions and procedures, and parameter passing by value and by reference in section 2.2.1, Programming techniques, in Component 02, Algorithms and programming.
AQA A Level Computer Science (7517): subroutines, parameters, return values, local and global variables, the role of the stack frame and recursive techniques appear in the fundamentals of programming section, assessed on Paper 1.