Skip to content
Cambridge AS & A Level9618

Recursion

Computer Science 9618 Chapter Notes

Last updated November 2026

ShareWhatsAppPost

Recursion notes as a printable PDF.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Recursion notes as text: skim, search, and jump between subtopics.

~15 min read

1. The essential features of recursion

Recursion is a process using a function or procedure that is defined in terms of itself. It calls itself.

A recursive process must have a base case: a way to return without making a recursive call. It must also have a general case, where the recursive call takes place.

Each call must change its state and move towards the base case.

``` FUNCTION Count(N : INTEGER) RETURNS INTEGER IF N = 0 THEN RETURN 0 ELSE RETURN 1 + Count(N - 1) ENDIF ENDFUNCTION ```

Here `N = 0` is the base case and `RETURN 1 + Count(N - 1)` is the general case.

Examiner insight

“Many of these candidates were also able to achieve the second mark by expanding on this, for example by describing the use of a base case.”

Worked example 13 marks

A stack is used to implement recursion.

State the three essential features of recursion.

  1. 1

    A recursive algorithm must call itself // have a general case [1]

  2. 2

    It must have a base case // have a stopping condition [1]

  3. 3

    It must change its state and move towards the base case [1]

2. Writing a recursive function

To turn a loop into recursion, replace the loop with a recursive call. Do not keep the loop inside the function: each call would then run it again.

Check the base case first and return a value from it. In the general case, return a value built from a call that has moved one step towards the base case, for example with a number one smaller or a string with one less character.

Every branch of a recursive function returns a value. A recursive version of a loop that totals divisors, for example, returns `Number + RecursiveValue(Number - 1, ToFind)` when `ToFind MODULUS Number = 0`, and `RecursiveValue(Number - 1, ToFind)` otherwise, with `Number = 0` as the base case.

Examiner insight

“Some candidates retained a loop within the function which meant each call would run several times.” “When candidates are given a pseudocode algorithm, they need to make sure they are copying the structure i.e. the parameters, the conditions, loops, calls etc.”

Worked example 16 marks

This iterative pseudocode algorithm for the function `IterativeVowels()` takes a string as a parameter and counts the number of lower-case vowels in this string. The vowels are the letters a, e, i, o and u.

``` FUNCTION IterativeVowels(Value : STRING) RETURNS INTEGER DECLARE Total : INTEGER DECLARE LengthString : INTEGER DECLARE FirstCharacter : CHAR Total ← 0 LengthString ← LENGTH(Value) FOR X ← 0 TO LengthString - 1 FirstCharacter ← MID(Value, 0, 1) IF FirstCharacter = 'a' OR FirstCharacter = 'e' OR FirstCharacter = 'i' OR FirstCharacter = 'o' OR FirstCharacter = 'u' THEN Total ← Total + 1 ENDIF Value ← MID(Value, 1, LENGTH(Value) - 1) NEXT X RETURN Total ENDFUNCTION ```

The pseudocode function `MID(X, Y, Z)` returns Z number of characters from string X, starting at the character in position Y. The first character in a string is in position 0. The pseudocode function `LENGTH(X)` returns the number of characters in the string X.

Rewrite the function `IterativeVowels()` as a recursive function with the identifier `RecursiveVowels()`.

  1. 1

    A recursive call [1]

  2. 2

    Function header taking a string parameter and returning an integer: `FUNCTION RecursiveVowels(Value : STRING) RETURNS INTEGER` [1]

  3. 3

    Base case: if the length is 0, return 0 [1]

  4. 4

    Extract the first character and check whether it is a vowel [1]

  5. 5

    If it is a vowel, return 1 + the recursive call with 1 less character [1]

  6. 6

    If not, return the recursive call with 1 less character [1]

3. Tracing a recursive function: winding and unwinding

A trace table gives a row to each call as it is made, then a row to each waiting call as it resumes. Going down, each call waits for the call below it: this is winding. At the base case the function returns without making a recursive call.

Coming back up, each waiting call receives a value and finishes: this is unwinding.

In the Fibonacci trace the first rows hold the calls that have not yet finished, and the last rows hold the results as they are returned.

Examiner insight

“Candidates generally appeared to find the trace of the given recursive function difficult.”

Worked example 15 marks

A Fibonacci sequence is a series of numbers formed by adding together the two preceding numbers, for example 0, 1, 1, 2, …

This function calculates and returns values in the Fibonacci sequence and uses recursion.

``` FUNCTION Fib(Number : INTEGER) RETURNS INTEGER IF Number <= 1 THEN Result ← Number ELSE Result ← Fib(Number – 1) + Fib(Number – 2) ENDIF RETURN Result ENDFUNCTION ```

Complete the trace table for the function when it is called as `Fib(5)`.

Call numberFunction callNumberResultReturn value
5
  1. 1

    Call number column correct: 1 to 6 while winding, then (4), (3), (2), (1) as the calls resume [1]

  2. 2

    Function call and Number columns correct: `Fib(5)` 5, `Fib(4)` 4, `Fib(3)` 3, `Fib(2)` 2, `Fib(1)` 1, `Fib(0)` 0, then `Fib(2)` 2, `Fib(3)` 3, `Fib(4)` 4, `Fib(5)` 5 [1]

  3. 3

    Result column while winding, rows 1 to 6: `Fib(4) + Fib(3)`, `Fib(3) + Fib(2)`, `Fib(2) + Fib(1)`, `Fib(1) + Fib(0)`, then 1 and 0 at the base cases [1]

  4. 4

    Result column while unwinding, rows 7 to 10: 1 + 0, 1 + 1, 2 + 1, 3 + 2 [1]

  5. 5

    Return value column correct: 1 and 0 at the base cases, then 1, 2, 3 and 5 as it unwinds [1]

4. Tracing a recursive procedure that changes an array

A procedure can change data as it recurses. Give the trace table the parameters first, here Index and Target, then one column for each array cell.

Write a value in a cell's column only when that cell changes. The mark scheme gives a mark for no incorrect data added to the columns that do not change.

The procedure below stops, with no further call, when `Numbers[Index]` is not greater than 0.

Worked example 14 marks

The recursive procedure `Delete()` is defined as follows:

``` PROCEDURE Delete(Index, Target) IF Numbers[Index] > 0 THEN IF Numbers[Index] >= Target THEN Numbers[Index] ← Numbers[Index + 1] ENDIF Index ← Index + 1 CALL Delete(Index, Target) ENDIF ENDPROCEDURE ```

An array `Numbers` is used to store a sorted data set of non-zero positive integers. Unused cells contain zero.

Complete the trace table for the algorithm for the procedure call `CALL Delete(1, 15)`. The contents of the array at the start of the algorithm are:

[1][2][3][4][5][6][7][8][9][10]
237111517192300
  1. 1

    Index and Target columns correct: Index 1 to 9, Target 15 [1]

  2. 2

    `Numbers[5]` column correct: 17 [1]

  3. 3

    `Numbers[6]` and `Numbers[7]` columns correct: 19 and 23 [1]

  4. 4

    `Numbers[8]` column correct: 0, and no incorrect data added to the columns for `Numbers[1]` to `Numbers[4]`, `Numbers[9]` and `Numbers[10]` [1]

5. When recursion is beneficial

Recursion is beneficial for problems that can be broken down into smaller, repetitive problems. It suits an algorithm when a problem naturally breaks down into smaller versions of itself.

It helps most for problems that have many possible branches, or that are too complex for an iterative approach.

Examples in the mark schemes: calculating a factorial, a mathematical series, Fibonacci, compound interest, tree traversal and the evaluation of RPN expressions.

Worked example 13 marks

Describe when the use of recursion would be beneficial and give an example.

  1. 1

    Recursion is beneficial for problems that can be broken down into smaller, repetitive problems [1]

  2. 2

    … especially for problems that have many possible branches, or are too complex for an iterative approach [1]

  3. 3

    An example, such as solving a mathematical series [1]

6. How a compiler translates recursive code

A compiler must produce object code that supports the recursive calls. That code uses a stack.

With each recursive call, the object code pushes return addresses and the values of local variables onto the stack. This is the winding.

After the base case is reached, the code pops the return addresses and values off the stack. This is the unwinding.

Examiner insight

“Candidates generally found this question challenging and simply explained recursion incorrectly.” “Candidates who began by stating that the compiler must produce object code and then explained how this code would be used to push return addresses onto a stack with each recursive call, then pop the return addresses from the stack after the base case is reached achieved the highest marks.”

Worked example 14 marks

Explain how a compiler makes use of a stack when translating recursive programming code.

  1. 1

    The compiler must produce object code to implement the recursion [1]

  2. 2

    … push return addresses / values of local variables onto a stack [1]

  3. 3

    … with each recursive call // to set up winding [1]

  4. 4

    … pop return addresses / values of local variables off the stack after the base case is reached // to implement unwinding [1]

Recap

  • Recursion: a function or procedure defined in terms of itself.
  • Essential features: it calls itself, it has a base case, and it moves towards the base case.
  • The base case returns without a recursive call. The general case makes the recursive call.
  • Trace a row for each call made, then a row as each waiting call resumes. Winding goes down to the base case. Unwinding returns the results.
  • Beneficial when a problem breaks into smaller repetitive problems or has many branches.
  • A compiler produces object code that pushes return addresses and local variable values onto a stack with each call.
  • The code pops them after the base case is reached, which implements unwinding.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. State what is meant by the base case of a recursive function.1 mark
    Answer
    1. The way to return without making a recursive call [1].

    Trap: The base case is not the line with the recursive call: that is the general case.

  2. Study the function. ``` FUNCTION Count(N : INTEGER) RETURNS INTEGER IF N = 0 THEN RETURN 0 ELSE RETURN 1 + Count(N - 1) ENDIF ENDFUNCTION ``` Identify the base case. Identify the general case. State the value returned by `Count(3)`.3 marks
    Answer
    1. Base case: `N = 0`, which returns 0 [1].
    2. General case: `RETURN 1 + Count(N - 1)` [1].
    3. Count(3) = 1 + Count(2) = 1 + 1 + Count(1) = 1 + 1 + 1 + Count(0) = 3 [1].

    Trap: The base case returns 0, but the answer is not 0: each waiting call adds 1 as it unwinds.

  3. Study the function. ``` FUNCTION Product(N : INTEGER) RETURNS INTEGER IF N <= 1 THEN RETURN 1 ELSE RETURN N * Product(N - 1) ENDIF ENDFUNCTION ``` Write the value returned by each call from `Product(1)` up to `Product(5)`, in the order they finish.3 marks
    Answer
    1. `Product(1)` returns 1 [1].
    2. `Product(2)` returns 2 × 1 = 2, `Product(3)` returns 3 × 2 = 6 [1].
    3. `Product(4)` returns 4 × 6 = 24, `Product(5)` returns 5 × 24 = 120 [1].

    Trap: The first call to finish is the base case, `Product(1)`. The call made first, `Product(5)`, finishes last.

  4. Study the procedure. ``` PROCEDURE Show(N : INTEGER) IF N > 0 THEN OUTPUT N CALL Show(N - 1) OUTPUT N ENDIF ENDPROCEDURE ``` Write the output of `CALL Show(3)`.3 marks
    Answer
    1. Winding: `Show(3)` outputs 3, `Show(2)` outputs 2, `Show(1)` outputs 1 [1].
    2. `Show(0)` is the base case and outputs nothing [1].
    3. Unwinding: `Show(1)`, `Show(2)` and `Show(3)` resume and output 1, 2, 3. The output is 3 2 1 1 2 3 [1].

    Trap: After the base case each waiting call resumes and runs its second `OUTPUT`. Stopping at 3 2 1 misses the unwinding.

  5. A programmer writes this function. ``` FUNCTION Sum(N : INTEGER) RETURNS INTEGER RETURN N + Sum(N - 1) ENDFUNCTION ``` Explain why a call `Sum(3)` never finishes properly. Describe how to correct the function.3 marks
    Answer
    1. There is no base case, so no call returns without making another recursive call [1].
    2. `N` goes 3, 2, 1, 0, −1 and so on, and never reaches a stopping condition [1].
    3. Add a base case, `IF N = 0 THEN RETURN 0`, with the recursive line in the `ELSE` [1].

    Trap: A base case must be reachable. `IF N = 100` would never be met because `N` decreases from 3.

  6. A programmer must search a folder that contains other folders, which contain further folders, to any depth. Explain why recursion suits this problem.3 marks
    Answer
    1. Searching one folder is a smaller version of searching the whole structure, so the problem breaks down into smaller repetitive problems [1].
    2. Each folder has many possible branches [1].
    3. The depth is not known, so an iterative approach is too complex [1].

    Trap: "Recursion is faster" gives no reason. Say what in the problem makes it suit recursion.

  7. Explain how a compiler makes use of a stack when it translates the function `Count()` from question 2, when the function is called as `Count(3)`.4 marks
    Answer
    1. The compiler must produce object code to implement the recursion [1].
    2. The object code pushes a return address and the value of the local variable `N` onto the stack [1].
    3. It does this with each recursive call: `Count(3)`, `Count(2)`, `Count(1)` and `Count(0)`. This is the winding [1].
    4. After the base case, `N = 0`, is reached, the return addresses and values are popped off the stack so each waiting call resumes. This is the unwinding [1].

    Trap: Explaining what recursion is scores nothing here. Say what the compiler's object code does with the stack.

  8. Write a recursive function `Power(Base, Exp)` that returns `Base` raised to the power `Exp`, for whole numbers with `Exp` 0 or more. Use multiplication and no loop. Show the value of `Power(2, 3)`.4 marks
    Answer
    1. ``` FUNCTION Power(Base : INTEGER, Exp : INTEGER) RETURNS INTEGER IF Exp = 0 THEN RETURN 1 ELSE RETURN Base * Power(Base, Exp - 1) ENDIF ENDFUNCTION ```
    2. Header with two parameters [1]; base case `Exp = 0` returning 1 [1]; general case `Base * Power(Base, Exp - 1)` [1].
    3. Power(2,3) = 2 × 2 × 2 × 1 = 8 [1].

    Trap: A base case that returns 0 makes every answer 0 because the results are multiplied. For a product the base case returns 1.

  9. The function `Fib` below is called as `Fib(4)`. ``` FUNCTION Fib(Number : INTEGER) RETURNS INTEGER IF Number <= 1 THEN Result ← Number ELSE Result ← Fib(Number – 1) + Fib(Number – 2) ENDIF RETURN Result ENDFUNCTION ``` State the value returned. State the total number of calls to `Fib`, counting the first call and counting repeated calls.4 marks
    Answer
    1. `Fib(4)` calls `Fib(3)` and `Fib(2)`; `Fib(3)` calls `Fib(2)` and `Fib(1)`; each `Fib(2)` calls `Fib(1)` and `Fib(0)` [1].
    2. Fib(2) = 1 + 0 = 1, Fib(3) = 1 + 1 = 2, Fib(4) = 2 + 1 = 3. The value returned is 3 [1].
    3. Calls: one `Fib(4)`, one `Fib(3)`, two `Fib(2)`, three `Fib(1)`, two `Fib(0)` [1].
    4. 1 + 1 + 2 + 3 + 2 = 9 calls [1].

    Trap: Counting five calls, `Fib(4)` down to `Fib(0)`, misses that `Fib(2)` and `Fib(1)` are each called again in another branch.

  10. A warehouse stores the number of boxes on each shelf in the global 1D array `Shelf`. This iterative function counts the empty shelves from shelf 1 to shelf `Last`. ``` FUNCTION CountEmpty(Last : INTEGER) RETURNS INTEGER DECLARE Total : INTEGER Total ← 0 FOR X ← 1 TO Last IF Shelf[X] = 0 THEN Total ← Total + 1 ENDIF NEXT X RETURN Total ENDFUNCTION ``` Rewrite `CountEmpty()` as a recursive function with the identifier `RecursiveEmpty()`. `Shelf` holds 3, 0, 5, 0, 0, 2 in cells 1 to 6. State the value returned by `RecursiveEmpty(6)` and the total number of calls to `RecursiveEmpty()`, counting the first call.7 marks
    Answer
    1. ``` FUNCTION RecursiveEmpty(Last : INTEGER) RETURNS INTEGER IF Last = 0 THEN RETURN 0 ELSE IF Shelf[Last] = 0 THEN RETURN 1 + RecursiveEmpty(Last - 1) ELSE RETURN RecursiveEmpty(Last - 1) ENDIF ENDIF ENDFUNCTION ```
    2. Header taking an integer parameter and returning an integer [1]; base case `Last = 0` returning 0 [1].
    3. Empty shelf: return 1 + the recursive call with `Last - 1` [1]; otherwise return the recursive call with `Last - 1` [1].
    4. No loop and no `Total` variable remain: the recursive call does the repeating [1].
    5. Unwinding: `RecursiveEmpty(0)` = 0, (1) = 0, (2) = 1, (3) = 1, (4) = 2, (5) = 3, (6) = 3. The value returned is 3 [1].
    6. Calls with `Last` = 6, 5, 4, 3, 2, 1 and 0: 7 calls [1].

    Trap: Examiners reported recursive rewrites that kept the loop or had no recursive call at all.

Say this, not that

Wording that loses the mark, against the wording the mark scheme credits.

Loses the markGets the mark
A recursive function calls itself.A recursive function calls itself and has a base case, a way to return without making a recursive call.
A recursive rewrite that repeats the loop and has no recursive callA function defined in terms of itself: the recursive call does the repeating.
A recursive rewrite that keeps its loop inside the functionThe recursive call replaces the loop: no loop remains in the function.
An explanation of what recursion is, when asked how the compiler uses a stackThe compiler produces object code that pushes return addresses onto a stack with each call and pops them after the base case.

Frequently asked questions

What are the essential features of a recursive function?
A recursive function or procedure is defined in terms of itself, so it calls itself. It must have a base case, a way to return without making a recursive call, and a general case, where the recursive call takes place. Each call must change its state and move towards the base case.
How do you write a recursive function from a loop?
Replace the loop with a recursive call. Do not keep the loop inside the function, because each call would then run it again. Check the base case first and return a value from it. In the general case, return a value built from a call that has moved one step towards the base case, with every branch returning a value.
How do you trace a recursive function with a trace table?
A trace table gives a row to each call as it is made, and this going down is winding. At the base case the function returns without making a recursive call. Coming back up, each waiting call receives a value and finishes, and this is unwinding. The trace shows the first rows as calls not yet finished and the last rows as results returned.
When is recursion beneficial?
Recursion is beneficial for problems that can be broken down into smaller, repetitive problems. It helps most for problems that have many possible branches, or that are too complex for an iterative approach. Examples include calculating a factorial, a mathematical series, Fibonacci, tree traversal and the evaluation of RPN expressions.
How does a compiler use a stack when it translates recursive code?
The compiler must produce object code that supports the recursive calls, and that code uses a stack. With each recursive call, the object code pushes return addresses and the values of local variables onto the stack. After the base case is reached, it pops them off the stack, which is the unwinding.
Is a recursive rewrite of a loop allowed to keep the loop inside the function?
No. Many candidates did not produce a recursive solution, and some kept a loop within the function, which meant each call would run several times. In a recursive rewrite the recursive call does the repeating, and no loop remains in the function.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters