الانتقال إلى المحتوى

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

Exam questions on what this lab teaches, with the points that gain marks.

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

  1. There must be a base case (a stopping condition).
  2. There must be a general case, which calls itself (is defined in terms of itself) …
  3. … and changes its state so it moves towards the base case. Unwinding happens once the base case is reached.
  4. A stack is a LIFO data structure.
  5. Each recursive call is pushed onto the stack, and popped when that call ends.
  6. 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

  1. (i) A function header that takes a string parameter and returns an integer.
  2. A base case: if the length is 0, return 0.
  3. Take the first character and check whether it is a vowel …
  4. … if it is, return 1 + the recursive call with one character fewer …
  5. … if not, return the recursive call with one character fewer.
  6. A recursive call.
  7. (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.

The question as printed in the exam paper

More real experiments

All labs →

تسجيل الدخول أو إنشاء حساب

IGCSE, A-Level & AP