Lesson contents

Recursion and the call stack

A recursive task does one small piece of work and calls itself on a simpler input. A base case tells it when to stop.

Simple example

Print the current number, then call the same countdown with one less. At zero, return without printing.

Start3
Result3 2 1
lesson.rb
def countdown(number)
  if number > 0
    puts number
    countdown(number - 1)
  end
end

countdown(3)
Output
3
2
1
Advertisements

Everyday examples

Count nested folders

A folder holds one smaller folder, which holds one empty folder. Where should the count stop?

StartA→B→C
Result3

Count the current folder once. At the empty folder there are no children to visit.

Open nested gift boxes

A box contains a smaller box, and the smallest contains a note. What is the base case?

Start□ → □ → ▤
Result▤

When the note appears, read it and return. There is no smaller box to open.

Pass a message down a line

Three students each say their number and pass the message to the next. What does the last one do?

Start3→2→1
Result1

Say one and stop. Passing it on again without checking would go beyond the line.

Cost and limits

Each unfinished call needs a place on the call stack. A very deep chain can exceed the language runtime’s stack limit.