CIE AS & A Level Computer Science, section 19.2 (Recursion)
What recursion is
A routine is recursive if it calls itself. Each call solves a smaller version of the same problem.
Two parts
- Base case: the simple case that has an answer without another call. It stops the recursion.
- General (recursive) case: the routine calls itself with a smaller or simpler argument, which moves it towards the base case.
Without a base case, the routine never stops (until it runs out of memory).
Example: factorial
and .
FUNCTION Factorial(N : INTEGER) RETURNS INTEGER
IF N = 0 THEN
RETURN 1 // base case
ELSE
RETURN N * Factorial(N - 1) // general case
ENDIF
ENDFUNCTION
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Example: sum of a list
def total(items):
if not items: # base case: empty list
return 0
return items[0] + total(items[1:])
print(total([4, 7, 1])) # 12
Example: Fibonacci
def fib(n):
if n <= 1:
return n # base cases
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(8)]) # [0, 1, 1, 2, 3, 5, 8, 13]
Recursion and iteration
Any recursive function can be written with a loop. Recursion is often shorter and clearer, but may use more memory.
Common mistake: missing the base case, or writing a recursive call that does not get closer to it, such as Factorial(N), which loops for ever. Also, the base case must return a value, not just stop.
Exam tip: name the base case and general case in your answer. Check that the argument gets smaller on each call.
Check yourself
What is the base case in a recursive function?
The case that is solved directly without a further recursive call, stopping the recursion.
What happens if a recursive function has no base case?
It calls itself repeatedly until memory for the calls runs out.
What is `factorial(3)`?
.