Skip to content

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.

Class 11 to 12intermediate30 min3 lessons
By the end you will be able to
  • State base case and recursive case in plain words
  • Trace a factorial or countdown recursion on paper
  • Explain why infinite recursion crashes the program

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.

Continue

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.

Continue

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.

Continue

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 attempted

Assessment

Check your understanding

Answer each question, then read the explanation. That is where the learning is.

0/4
  1. Question 1: A base case in recursion is what?
    Question 1 / 4

    A base case in recursion is what?

    Select an option first
  2. Question 2: factorial(n) = n * factorial(n-1) with factorial(1)=1 is an example of what?
    Question 2 / 4

    factorial(n) = n * factorial(n-1) with factorial(1)=1 is an example of what?

    Select an option first
  3. Question 3: Stack overflow in recursion usually means what?
    Question 3 / 4

    Stack overflow in recursion usually means what?

    Select an option first
  4. Question 4: Maze backtracking relates to recursion because what?
    Question 4 / 4

    Maze backtracking relates to recursion because what?

    Select an option first
4 of 4 questions left.

Finished this topic?

0 of 3 lessons marked done. Marking the topic complete ticks the rest.