Recursion: Functions That Call Themselves
A function can call itself on a smaller piece of the problem. You need a base case that stops, or the stack overflows.
- State base case and recursive case in plain words
- Trace a factorial or countdown recursion on paper
- Explain why infinite recursion crashes the program
Finish first
Topic contents
Lesson 1 of 3
Smaller versions of the same task
Factorial of 5 is 5 times factorial of 4. Factorial of 4 is 4 times factorial of 3. The pattern repeats until factorial of 1, which is defined as 1. That bottom definition is the base case.
Each call waits for a smaller call to finish. The call stack remembers where to resume. Too many calls without a base case overflow the stack.
Watch the step-flow animation. See factorial(4) peel down to 1, then multiply on the way back up.
Lesson 2 of 3
Trees and mazes already taught you
Backtracking in the maze lab was recursion in disguise: try a path, undo, try another. Tree traversals call left and right subtrees the same way.
Board exam questions often ask trace this recursive function. Write stack frames on paper.
Binary search is iterative in our lab, but its divide-half idea pairs naturally with recursive thinking too.
Lesson 3 of 3
Bridge to dynamic programming
Naive Fibonacci recursion recomputes the same values many times. That waste sets up the next topic: remember answers you already calculated.
Recursion is not always the fastest tool, but it is often the clearest way to state a problem.
Next: memoisation turns repeated subproblems into a table lookup.
Practice
Work these out yourself
No answer key here on purpose: these are the questions worth thinking through before you move on. Open one and work it out.
0/3 attemptedAssessment
Check your understanding
Answer each question, then read the explanation. That is where the learning is.
Finished this topic?
0 of 3 lessons marked done. Marking the topic complete ticks the rest.
