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.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

fn countdown(number: i64) anyerror!void {
    if (number > 0) {
        try show(number);
        try countdown(number - 1);
    }
}

pub fn main() !void {
    try 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.