Passer au contenu

Labs · 9618 A2 19.2

Recursion and the Call Stack

Drive a recursive function yourself: call it again or return a value, step by step. Watch the call stack grow to the base case and unwind.

6 levelsFree bench

In the exam

9618/31 October/November 2021 · Question 10(a) and (b) · 6 marks

(a) State three essential features of recursion. (b) Explain the reasons why a stack is a suitable Abstract Data Type (ADT) to implement recursion.

Points that gain marks

  • There must be a base case (a stopping condition).
  • There must be a general case, which calls itself (is defined in terms of itself) …
  • … and changes its state so it moves towards the base case. Unwinding happens once the base case is reached.
  • A stack is a LIFO data structure.
  • Each recursive call is pushed onto the stack, and popped when that call ends.
  • This allows the unwinding (backtracking) in the right order.

In this lab: Every level shows the stack: a frame is pushed at each call and popped at each return, last in, first out.

9618/41 October/November 2023 · Question 1(b) · 8 marks

(i) Rewrite the function IterativeVowels() as a recursive function RecursiveVowels(). (ii) Call RecursiveVowels() with the parameter "imagine" from the main program and output the return value. (iii) Test your program.

Points that gain marks

  • (i) A function header that takes a string parameter and returns an integer.
  • A base case: if the length is 0, return 0.
  • Take the first character and check whether it is a vowel …
  • … if it is, return 1 + the recursive call with one character fewer …
  • … if not, return the recursive call with one character fewer.
  • A recursive call.
  • (ii) Call it with "imagine" and output the return value. (iii) The output is 4.

In this lab: Level 3 runs this function letter by letter.

More real experiments

Se connecter ou créer un compte

IGCSE, A-Level & AP