Chapter 6

Recursion and return-value tracing

Separate three questions: does the call terminate, what value does it return, and how much work or stack does it use? Write a recurrence only after tracing the exact base case and all direct recursive calls.

6.1 Termination and return order

Past papers · CS 2014–2026 (23 papers): 6 questions, 11 marks

A base case must be reachable from the stated input. For positive integer division, repeatedly halving eventually reaches zero; a base case testing only negativity will not stop that chain. With mutual recursion, examine a complete cycle across functions to find net progress.

Output before a recursive call follows descent order; output after it follows return order. Each frame retains its own arguments and local bindings. If a function computes two recursive values, do not silently replace the second call by the first call's answer when shared state can change.

6.2 Recursion counts and standard patterns

Past papers · CS 2014–2026 (23 papers): 3 questions, 5 marks

For Fibonacci-like recursion, distinguish the returned-value recurrence from the call-count recurrence: the latter includes an extra one for the present call. For a loop that recursively calls every smaller argument, include every loop iteration in the recurrence. If a call uses two endpoints only through interval length, reduce the state to that length and examine its residue classes: a branch may add once, then force all later calls into branches that add nothing. A returned sum, number of leaves and number of calls need not coincide. General recurrence methods belong to the Algorithms handbook.

6.3 Accumulators and polynomial evaluation

Past papers · CS 2014–2026 (23 papers): 10 questions, 17 marks · DA 2024–2026 (3 papers): 1 question, 2 marks

A recursive return can accumulate a sum, maximum, count of runs, or digit value. Define the value for the empty suffix explicitly. For example, a run count on a nonempty array returns 1 for a one-element suffix, adds 1 where adjacent items differ, and otherwise skips without increment. A maximum initialised to zero gives wrong results on an all-negative input unless zero is intentionally part of the candidates.

Last-minute recall

  • Check that the base condition is reachable.
  • Draw separate local state for separate frames.
  • Shared mutable state can affect later calls.
  • Add one for the current activation when counting calls.
  • Sequential child stack depths combine by maximum, not sum.
  • Count local work as well as recursive calls.
  • Simplify a return recurrence only after including all initial terms.

Revise offline: the whole Programming and Data Structures handbook as one PDF

55 pages · 2.6 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections