Recursion & Call Stack

HKDSE ICT - Algorithm & Programming

Learning Objectives

Deep Dive: What is Recursion?

In programming, Recursion occurs when a subroutine calls itself directly or indirectly during execution. It is a problem-solving strategy that breaks down a large problem into smaller Sub-problems of the same structure.

To write a correct recursive function, two core elements are required:

Base Case

The terminating condition. When met, the function stops calling itself and returns a definite value. Without it, infinite recursion occurs.

Recursive Step

Simplifies the problem and calls itself with a smaller parameter. Each recursive call must move the state closer to the Base Case.

Interactive Simulation: Factorial

Formula: $$n! = n \times (n-1)!$$, Base Case: $$1! = 1$$


def factorial(n):
if n == 1: # Base Case
return 1
# Recursive Step
return n * factorial(n - 1)

Execution Log

Step 1 / 10

💡 Tip: Use Left/Right arrow keys to control.

Call Stack

Follows LIFO (Last-In-First-Out). Memory allocates an independent space (Stack Frame) for each call.

Stack is empty

Common Myths

Myth: Recursion is always better than Iteration (like for/while loops)?

Fact: Not necessarily. While recursion makes code cleaner for trees or graphs, its Space Complexity is higher because each call creates a new Stack Frame. Deep recursion exhausts memory, causing a Stack Overflow runtime error. Iteration is often more memory-efficient.

Key Takeaways

  • Recursion inherently relies on the computer's Call Stack to pause and save states.
  • A Base Case is mandatory as the 'brake system'; otherwise, the program crashes.
  • The process has two phases: 'Winding' (pushing calls onto the stack) and 'Unwinding' (popping calls and returning values after reaching the base case).

Think & Link

Q: What happens under the hood if we forget the `if (n == 1)` base case when calculating `factorial(3)`?

A: The function endlessly calls `factorial(0)`, `factorial(-1)`... Each call consumes a block of Call Stack memory. Since memory is finite, the computer eventually exhausts it and throws a Stack Overflow runtime error, crashing the program.

Self-Assessment

1. What element is essential to prevent a recursive function from infinite execution?

2. Which data structure does the computer underlyingly use to record return addresses and variables of Subroutines?