Computer ScienceCore22 min read

Recursion

A routine that calls itself, and the stack that makes it possible

This topic appears in:

01

Defining something in terms of itself

A recursive routine is one that calls itself. That sounds circular, and it would be, except for one requirement: every recursive definition must contain a base case — a situation it can answer directly without calling itself again.

Each call must also move towards that base case. Together these two conditions guarantee the process terminates. Remove either and the routine calls itself forever, which in practice means the call stack fills and the program crashes with a stack overflow.

Both conditions are examined. "It must have a base case" earns half the marks; the other half is for the progress towards it.

every recursive routine needs:1. a BASE CASE that returns without recursing2. a RECURSIVE CASE that moves towards itfactorial:F(1) = 1base caseF(n) = n × F(n − 1)recursive casewithout a base case the recursion never stops
base case
the stopping conditionanswered directly, with no further call
recursive case
the self-callmust use a smaller or simpler argument
stack overflow
the failure modewhat happens when it never terminates

Recursion is easiest to follow as a trace: each call is pushed and waits, and nothing is computed on the way down. The answers are built on the way back up, once the base case has been reached.

02

The stack is what makes it work

When a routine calls another, the computer must remember where to come back to. It pushes a stack frame holding the return address, the parameters and the local variables. When the call finishes, the frame is popped and execution resumes.

Recursion uses exactly the same mechanism, just with the routine calling itself. Computing F(4) pushes frames for 4, 3, 2 and 1. Nothing is calculated on the way down — each call is suspended waiting on the next. Only when the base case returns does the answer travel back up, each frame completing its multiplication as it is popped.

This is why deep recursion is expensive: every level costs a frame of memory, and there is a limit. It is also why the stack is a last in, first out structure — the most recent call must finish first.

Worked example

Trace the calls and returns for the recursive factorial function F(n) = n × F(n−1), with F(1) = 1, when called as F(4).

  1. F(4) is called. It cannot return yet — it needs F(3). A frame is pushed.The multiplication 4 × F(3) cannot happen until F(3) is known.
  2. F(3) calls F(2), which calls F(1). Four frames are now on the stack.Each call suspends and waits. Nothing has been calculated yet.
  3. F(1) = 1 — the base case returns directly without recursing.This is what stops the descent and starts the unwinding.
  4. F(2) = 2 × 1 = 2, and its frame is popped.Now that F(1) has returned, F(2) can complete its multiplication.
  5. F(3) = 3 × 2 = 6, then F(4) = 4 × 6 = 24.Each frame completes in reverse order of calling — last in, first out.

F(4) = 24, with four frames pushed and popped in reverse order

Nothing is computed on the way down

A common misunderstanding is that each call does part of the work as it descends. It does not — every call is suspended at the point of the recursive call, waiting. All the arithmetic happens during the return journey, after the base case. Tracing questions are marked on exactly this ordering.

03

Recursion or iteration?

Anything expressible recursively can be written iteratively and vice versa, so the choice is about clarity and cost rather than capability.

Recursion is far more readable when the problem itself is recursive — walking a tree, traversing a directory of directories, or a divide-and-conquer algorithm such as quicksort or binary search. Iteration is more efficient for simple repetition, because it uses no stack frames.

RecursionIteration
Memorya stack frame per callconstant
Speedslower — call overheadfaster
Riskstack overflow if too deepinfinite loop, but no crash
Readabilityexcellent for recursive structuresbetter for simple repetition
Typical usetrees, quicksort, binary searchcounting, summing, scanning a list

What to say in an exam

  1. Every recursive routine needs a base case and progress towards it.
  2. Without both, the stack fills and the program crashes with a stack overflow.
  3. Each call pushes a frame holding the return address, parameters and locals.
  4. The stack is LIFO, so the most recent call completes first.
  5. Nothing is computed on the way down; the work happens on the way back.
  6. Recursion suits recursive data structures; iteration is cheaper for plain repetition.
04

Converting between recursion and iteration

Because both can express any computation, questions often ask for one rewritten as the other. The conversion is mechanical once the structure is recognised.

Turning recursion into iteration means replacing the implicit stack with an explicit loop. For a simple accumulating recursion such as factorial, a single loop with a running total is enough, because there is nothing to remember beyond that total. For a branching recursion such as a tree traversal, the stack must be recreated explicitly with a stack data structure — which is precisely why recursion is preferred there.

Turning iteration into recursion means making the loop variable a parameter and the loop's exit condition the base case. What the loop body accumulated becomes what the recursive call returns.

RECURSIVEITERATIVEFUNCTION Fact(n)FUNCTION Fact(n)IF n = 1 THENtotal ← 1RETURN 1FOR i ← 2 TO nELSEtotal ← total × iRETURN n * Fact(n-1)NEXT iENDIFRETURN totalENDFUNCTIONENDFUNCTIONsame result; the loop needs no stack framesthe base case becomes the loop initialisation and exit condition
base case
becomesthe starting value and the loop bound
recursive call
becomesthe next iteration of the loop
stack frames
becomea single accumulating variable

When the conversion is not worth doing

For factorial the iterative version is plainly better — same result, no stack cost. For a tree traversal the iterative version needs an explicit stack that the programmer has to push and pop by hand, which is longer, harder to read and easier to get wrong than simply letting the language's own call stack do the job. The right answer to "should this be rewritten iteratively" depends entirely on whether the problem is itself recursive.

Practice questions

5 questions · 15 marks · full working on every one

Try each one on paper first, then open the working. The marks are shown where they are actually awarded, because that is where they are actually lost.

Short questions

4 · 9 marks

Two marks each, in the style of the short-question section of the paper. Answer in two or three lines.

SQ1[2 marks]
State the two conditions a recursive routine must satisfy in order to terminate.
Model answer

It must have a base case that returns a value without calling itself, and each recursive call must make progress towards that base case — typically by reducing the parameter.

Examiner tip. One mark each. Stating only the base case is the usual half answer.

SQ2[3 marks]
Explain the role of the stack when a recursive routine executes.
Model answer

Each call pushes a stack frame containing the return address, the parameters and any local variables, so the suspended call can be resumed. Frames accumulate as the recursion descends. When the base case returns, the frames are popped in reverse order — last in, first out — with each completing its calculation as it goes.

Examiner tip. Three marks: what a frame holds, that frames accumulate, and the LIFO unwinding.

SQ3[2 marks]
A recursive function is written with no base case. Describe what happens when it runs.
Model answer

It calls itself indefinitely, pushing a new stack frame each time and never returning. The stack eventually runs out of memory and the program terminates with a stack overflow error.

Examiner tip. Both the endless calling and the named consequence are needed.

SQ4[2 marks]
Give one situation where recursion is clearly preferable to iteration, and one where iteration is preferable.
Model answer

Recursion is preferable for recursive data structures such as traversing a tree, or for divide-and-conquer algorithms like quicksort, where an iterative version would need an explicit stack of its own. Iteration is preferable for simple repetition such as summing a list, where recursion would waste memory on stack frames for no gain in clarity.

Examiner tip. A named example of each secures both marks.

Exam questions

1 · 6 marks

Multi-part questions with a full mark scheme.

Q1[6 marks]
A function is defined as: S(1) = 1, and S(n) = n + S(n−1) for n > 1.
(a) State the base case and the recursive case.
(b) Trace S(5), showing the calls and the returns.
(c) Give one advantage and one disadvantage of using recursion here rather than a loop.
Mark scheme
  1. (a) Base case: S(1) = 1. Recursive case: S(n) = n + S(n−1).Both must be identified separately.[1]
  2. (b) S(5) calls S(4), which calls S(3), S(2) and finally S(1). Five frames are pushed.The descent, with nothing computed yet.[1]
  3. S(1) returns 1 — the base case.This starts the unwinding.[1]
  4. S(2) = 2 + 1 = 3; S(3) = 3 + 3 = 6; S(4) = 4 + 6 = 10; S(5) = 5 + 10 = 15.Returns in reverse order of the calls.[1]
  5. (c) Advantage: the code closely matches the mathematical definition, so it is shorter and clearer.Readability is the usual advantage.[1]
  6. Disadvantage: each call uses a stack frame, so it needs more memory and risks stack overflow for large n.Memory cost is the standard disadvantage.[1]

(a) S(1)=1 and S(n)=n+S(n−1); (b) S(5) = 15; (c) clarity vs stack memory