Zig Exercises
Reading code is one thing. Writing it from an empty file is where it sticks. This page has 23 exercises that cover the whole tutorial, from loops and strings to allocators, error handling, comptime and threads. They’re grouped into beginner, intermediate and advanced, and each one links to the lesson it practises.
How to get the most out of them:
- Try first. Write your own version and run it with
zig run main.zigbefore you open the solution. - Read the errors. In Zig, a compile error is part of the exercise. The messages are precise, and the compiler errors pages explain the common ones.
- Compare, don’t copy. Your solution may look different from ours and still be right. If it builds and the output matches, you’ve done it.
Every solution below was compiled and run with Zig 0.17.1, and the output shown is what it printed.
Beginner
Section titled “Beginner”1. Temperature table
Section titled “1. Temperature table”Print a table of Celsius temperatures from 0 to 40 in steps of 10, with the Fahrenheit value next to each (F = C * 1.8 + 32). Line the numbers up in columns. Practises Zig While and Zig Type Casting.
Hint: a while loop with a continue expression, : (c += 10), steps by 10. Turn the integer into a float with @floatFromInt before you multiply. A width like {d:>3} pads a number on the left.
Show solution
const std = @import("std");
pub fn main() void { var c: u32 = 0; while (c <= 40) : (c += 10) { const f = @as(f64, @floatFromInt(c)) * 1.8 + 32; std.debug.print("{d:>3} C = {d:>5.1} F\n", .{ c, f }); }}Output:
0 C = 32.0 F 10 C = 50.0 F 20 C = 68.0 F 30 C = 86.0 F 40 C = 104.0 F@floatFromInt needs to know which float you want, so @as(f64, ...) gives it the type. {d:>5.1} means “right-aligned, 5 wide, 1 decimal place”.
One surprise we hit while writing this: if c is an i32 instead of a u32, a padded number prints with a plus sign (+10). Zig shows the sign of a signed number when you give it a width. Use an unsigned type when the value can’t be negative.
2. FizzBuzz
Section titled “2. FizzBuzz”Write a function fizzbuzz(n: u32) void that prints Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise. Call it for 1 to 15. Practises Zig If…Else and Zig Functions.
Hint: check 15 first. for (1..16) |i| counts from 1 to 15, but i is a usize, so convert it with @intCast.
Show solution
const std = @import("std");
fn fizzbuzz(n: u32) void { if (n % 15 == 0) { std.debug.print("FizzBuzz\n", .{}); } else if (n % 3 == 0) { std.debug.print("Fizz\n", .{}); } else if (n % 5 == 0) { std.debug.print("Buzz\n", .{}); } else { std.debug.print("{d}\n", .{n}); }}
pub fn main() void { for (1..16) |i| { fizzbuzz(@intCast(i)); }}Output:
12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzzIf you check % 3 before % 15, then 15 prints Fizz: order matters in an if/else if chain. The range 1..16 stops before 16, just like slices do.
3. Class scores
Section titled “3. Class scores”Given const scores = [_]u32{ 72, 85, 90, 64, 99 };, print the average (one decimal place) and the best score. Write the average as a function that takes a slice, so it works for any number of scores. Practises Zig Arrays and Zig Slices.
Hint: a function parameter of type []const u32 accepts &scores. Add up the scores as integers, then convert both the total and scores.len to f64 before dividing.
Show solution
const std = @import("std");
fn average(scores: []const u32) f64 { var total: u32 = 0; for (scores) |s| total += s; return @as(f64, @floatFromInt(total)) / @as(f64, @floatFromInt(scores.len));}
pub fn main() void { const scores = [_]u32{ 72, 85, 90, 64, 99 }; var best: u32 = 0; for (scores) |s| { if (s > best) best = s; } std.debug.print("average: {d:.1}\n", .{average(&scores)}); std.debug.print("best: {d}\n", .{best});}Output:
average: 82.0best: 99&scores turns the array into a slice, which carries its own length. Integer / would throw away the decimals, so the division happens on floats.
4. Count the vowels
Section titled “4. Count the vowels”Write countVowels(text: []const u8) usize that counts a, e, i, o and u, in upper or lower case. Test it with "Hello, Zig" and "rhythm". Practises Zig Strings and Zig Switch.
Hint: a string is a slice of bytes, so for (text) |c| gives you one byte at a time. A switch prong can list several values: 'a', 'e' => ....
Show solution
const std = @import("std");
fn countVowels(text: []const u8) usize { var count: usize = 0; for (text) |c| { switch (c) { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' => count += 1, else => {}, } } return count;}
pub fn main() void { std.debug.print("{d}\n", .{countVowels("Hello, Zig")}); std.debug.print("{d}\n", .{countVowels("rhythm")});}Output:
30A switch on a u8 must handle every possible byte, so else => {} covers “everything else, do nothing”. This counts bytes, which is fine for English text. Letters like é take two bytes in UTF-8 and wouldn’t be counted.
5. Reverse a word in place
Section titled “5. Reverse a word in place”Write reverse(text: []u8) void that reverses the bytes of a string without making a copy. Use it to turn "stressed" into "desserts". Practises Zig While and Zig Strings in Depth.
Hint: a string literal is read-only, so copy it into a variable array first with var word = "stressed".*;. Then swap from both ends towards the middle.
Show solution
const std = @import("std");
fn reverse(text: []u8) void { if (text.len < 2) return; var left: usize = 0; var right: usize = text.len - 1; while (left < right) : ({ left += 1; right -= 1; }) { const tmp = text[left]; text[left] = text[right]; text[right] = tmp; }}
pub fn main() void { var word = "stressed".*; reverse(&word); std.debug.print("{s}\n", .{word});}Output:
dessertsThe early return matters: for an empty string, text.len - 1 would overflow, because usize can’t go below zero. The continue expression can be a block, so it can update both indexes. In real code, std.mem.reverse(u8, &word) does the same job.
6. Fix the compile errors
Section titled “6. Fix the compile errors”This program doesn’t build. Fix every error without changing what it prints (total: 36). Practises Zig Variables.
const std = @import("std");
pub fn main() void { var price = 12; var total: u32 = 0; const discount = 5; for (0..3) |i| { total += price; } std.debug.print("total: {d}\n", .{total});}Zig 0.17.1 says:
main.zig:7:17: error: unused capture for (0..3) |i| { ^main.zig:6:11: error: unused local constant const discount = 5; ^~~~~~~~main.zig:4:9: error: local variable is never mutated var price = 12; ^~~~~main.zig:4:9: note: consider using 'const'Hint: read the errors one at a time. Zig doesn’t allow unused names, and a var that never changes should be a const.
Show solution
const std = @import("std");
pub fn main() void { const price = 12; var total: u32 = 0; for (0..3) |_| { total += price; } std.debug.print("total: {d}\n", .{total});}Output:
total: 36Three fixes: price becomes const, the unused discount goes, and the unused loop capture becomes _. Zig is strict about this on purpose: an unused variable is often a bug, like a value you meant to use and forgot.
7. Find a fruit
Section titled “7. Find a fruit”Write findIndex(items: []const []const u8, wanted: []const u8) ?usize that returns the position of wanted, or null if it isn’t there. Look for "cherry" and "mango" in a list of fruits. Practises Zig Optionals.
Hint: compare strings with std.mem.eql(u8, a, b), never with ==. for (items, 0..) |item, i| gives you the index too.
Show solution
const std = @import("std");
fn findIndex(items: []const []const u8, wanted: []const u8) ?usize { for (items, 0..) |item, i| { if (std.mem.eql(u8, item, wanted)) return i; } return null;}
pub fn main() void { const fruits = [_][]const u8{ "apple", "banana", "cherry" }; const a = findIndex(&fruits, "cherry") orelse 999; std.debug.print("cherry is at {d}\n", .{a}); if (findIndex(&fruits, "mango")) |i| { std.debug.print("mango is at {d}\n", .{i}); } else { std.debug.print("no mango\n", .{}); }}Output:
cherry is at 2no mangoThe solution shows both ways to open an optional: orelse gives a fallback value, and if (x) |i| runs a block only when there’s a value.
Intermediate
Section titled “Intermediate”8. Safe division
Section titled “8. Safe division”Write divide(a: i32, b: i32) MathError!i32 that returns error.DivisionByZero when b is 0. Call it on 10 / 2, 7 / 0 and -9 / 2, and print either the result or the error name. Practises Zig Errors and Zig Try & Catch.
Hint: signed integer division needs @divTrunc or @divFloor. Use catch |err| { ...; continue; } inside the loop to handle a failure and move on.
Show solution
const std = @import("std");
const MathError = error{DivisionByZero};
fn divide(a: i32, b: i32) MathError!i32 { if (b == 0) return error.DivisionByZero; return @divTrunc(a, b);}
pub fn main() void { const pairs = [_][2]i32{ .{ 10, 2 }, .{ 7, 0 }, .{ -9, 2 } }; for (pairs) |p| { const result = divide(p[0], p[1]) catch |err| { std.debug.print("{d} / {d}: {t}\n", .{ p[0], p[1], err }); continue; }; std.debug.print("{d} / {d} = {d}\n", .{ p[0], p[1], result }); }}Output:
10 / 2 = 57 / 0: DivisionByZero-9 / 2 = -4{t} prints the error’s name. @divTrunc rounds towards zero, so -9 / 2 gives -4. With @divFloor you’d get -5.
9. Bank account
Section titled “9. Bank account”Make an Account struct with an owner and a balance (default 0), plus two methods: deposit and withdraw. withdraw returns error.InsufficientFunds if there isn’t enough money. Practises Zig Structs and Zig Struct Methods.
Hint: methods that change the struct take self: *Account. The return type error{InsufficientFunds}!void means “nothing, or this error”.
Show solution
const std = @import("std");
const Account = struct { owner: []const u8, balance: u64 = 0,
fn deposit(self: *Account, amount: u64) void { self.balance += amount; }
fn withdraw(self: *Account, amount: u64) error{InsufficientFunds}!void { if (amount > self.balance) return error.InsufficientFunds; self.balance -= amount; }};
pub fn main() void { var acc: Account = .{ .owner = "Ada" }; acc.deposit(100); acc.withdraw(30) catch unreachable; std.debug.print("{s} has {d}\n", .{ acc.owner, acc.balance });
acc.withdraw(500) catch |err| { std.debug.print("withdraw 500: {t}\n", .{err}); }; std.debug.print("{s} still has {d}\n", .{ acc.owner, acc.balance });}Output:
Ada has 70withdraw 500: InsufficientFundsAda still has 70acc must be var, because the methods change it through a pointer. catch unreachable says “I know this can’t fail here”: fine for a withdrawal you’ve just checked, but in a debug build it panics if you’re wrong.
10. Shapes
Section titled “10. Shapes”Make a tagged union Shape with three kinds: circle (a radius), rect (a width and a height) and square (a side). Give it an area method and print the area of one of each. Practises Zig Tagged Unions.
Hint: union(enum) makes a tagged union. Inside area, switch (self) and capture each payload with |r|.
Show solution
const std = @import("std");
const Shape = union(enum) { circle: f64, // radius rect: struct { w: f64, h: f64 }, square: f64, // side
fn area(self: Shape) f64 { return switch (self) { .circle => |r| std.math.pi * r * r, .rect => |r| r.w * r.h, .square => |s| s * s, }; }};
pub fn main() void { const shapes = [_]Shape{ .{ .circle = 1.0 }, .{ .rect = .{ .w = 2, .h = 3 } }, .{ .square = 4 }, }; for (shapes) |s| { std.debug.print("{t}: {d:.2}\n", .{ s, s.area() }); }}Output:
circle: 3.14rect: 6.00square: 16.00If you add a fourth shape later and forget to update area, the switch stops compiling until you handle it. That’s the big win of tagged unions over a plain struct with a “kind” field. {t} on a tagged union prints the active tag’s name.
11. Collect the even numbers
Section titled “11. Collect the even numbers”Use an ArrayList to collect the even numbers from 1 to 20, then print how many there are and the list itself. Use the allocator from main’s init. Practises Zig ArrayList and Zig Main & Init.
Hint: in Zig 0.17 an ArrayList starts as .empty, and you pass the allocator to every call that might allocate: append(gpa, x) and deinit(gpa).
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var evens: std.ArrayList(u32) = .empty; defer evens.deinit(gpa);
for (1..21) |i| { const n: u32 = @intCast(i); if (n % 2 == 0) try evens.append(gpa, n); }
std.debug.print("{d} evens: {any}\n", .{ evens.items.len, evens.items });}Output:
10 evens: { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }defer evens.deinit(gpa) sits right under the declaration, so you can’t forget it. init.gpa reports leaks in debug builds, so if you remove that line, you’ll see a leak report when the program ends.
12. Count words
Section titled “12. Count words”Count how often each word appears in "the cat and the dog and the bird". Then print the counts for the, and, cat and fish (which should be 0). Practises Zig HashMap and Zig Strings in Depth.
Hint: std.mem.tokenizeScalar(u8, text, ' ') splits on spaces. getOrPut finds a key or makes room for it in one step, and found_existing tells you which happened.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const text = "the cat and the dog and the bird";
var counts: std.StringHashMapUnmanaged(u32) = .empty; defer counts.deinit(gpa);
var words = std.mem.tokenizeScalar(u8, text, ' '); while (words.next()) |word| { const entry = try counts.getOrPut(gpa, word); if (entry.found_existing) { entry.value_ptr.* += 1; } else { entry.value_ptr.* = 1; } }
for ([_][]const u8{ "the", "and", "cat", "fish" }) |w| { std.debug.print("{s}: {d}\n", .{ w, counts.get(w) orelse 0 }); }}Output:
the: 3and: 2cat: 1fish: 0The map stores the word slices, not copies. That’s fine here because text lives for the whole program. If the words came from a buffer you reuse, you’d have to copy each key first. Printing the map in a loop would give the words in no fixed order, which is why the solution asks for specific words.
13. Leaderboard
Section titled “13. Leaderboard”Sort a list of players by score, highest first, and print them with their rank. Two players have the same score: keep them in their original order. Practises Zig Sorting & Searching.
Hint: std.mem.sort(T, slice, context, lessThan). Your lessThan returns true when a should come before b. Use > (not >=), and std.mem.sort keeps equal items in order because it’s a stable sort.
Show solution
const std = @import("std");
const Player = struct { name: []const u8, score: u32,};
fn byScoreDesc(_: void, a: Player, b: Player) bool { return a.score > b.score;}
pub fn main() void { var players = [_]Player{ .{ .name = "Ana", .score = 40 }, .{ .name = "Ben", .score = 75 }, .{ .name = "Cy", .score = 40 }, .{ .name = "Di", .score = 90 }, }; std.mem.sort(Player, &players, {}, byScoreDesc); for (players, 1..) |p, rank| { std.debug.print("{d}. {s} ({d})\n", .{ rank, p.name, p.score }); }}Output:
1. Di (90)2. Ben (75)3. Ana (40)4. Cy (40)The context here is {} (nothing), so the first parameter of byScoreDesc is _: void. Ana stays before Cy because the sort is stable.
14. A times table on stdout
Section titled “14. A times table on stdout”Print the 7 times table (1 to 5) to stdout, not stderr, using a buffered writer. Practises Zig Output and Zig Readers & Writers.
Hint: get a writer with std.Io.File.stdout().writer(init.io, &buf) and take a pointer to its interface. Don’t forget the last step.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { var buf: [256]u8 = undefined; var stdout = std.Io.File.stdout().writer(init.io, &buf); const out = &stdout.interface;
for (1..6) |i| { try out.print("{d} x 7 = {d}\n", .{ i, i * 7 }); } try out.flush();}Output:
1 x 7 = 72 x 7 = 143 x 7 = 214 x 7 = 285 x 7 = 35The “last step” is try out.flush(). The text collects in buf and only reaches the terminal when you flush. Forget it and the program prints nothing at all, with no error.
15. Find the leak
Section titled “15. Find the leak”This program prints the right thing, but it leaks memory. Find the leak and fix it with one line. Practises Zig Memory Leaks and Zig Allocators.
const std = @import("std");
fn shout(gpa: std.mem.Allocator, text: []const u8) ![]u8 { const loud = try gpa.alloc(u8, text.len); for (text, loud) |c, *out| out.* = std.ascii.toUpper(c); return loud;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; for ([_][]const u8{ "hello", "zig" }) |word| { const loud = try shout(gpa, word); std.debug.print("{s}\n", .{loud}); }}When it ends, you’ll see something like this (addresses and paths change on every run):
HELLOZIGerror(SafeAllocator): leaked [addr: 7fd489695960, len: 3 (0x3) align: 1] allocated at:main.zig:4:31: 0x11e41ac in shout (main.zig) const loud = try gpa.alloc(u8, text.len); ^main.zig:12:31: 0x11e450b in main (main.zig) const loud = try shout(gpa, word); ^Hint: shout allocates and hands the memory to its caller. So who has to free it? The report points at the exact line that allocated.
Show solution
const std = @import("std");
fn shout(gpa: std.mem.Allocator, text: []const u8) ![]u8 { const loud = try gpa.alloc(u8, text.len); for (text, loud) |c, *out| out.* = std.ascii.toUpper(c); return loud;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; for ([_][]const u8{ "hello", "zig" }) |word| { const loud = try shout(gpa, word); defer gpa.free(loud); std.debug.print("{s}\n", .{loud}); }}Output:
HELLOZIGA function that returns allocated memory gives ownership to the caller, so the caller frees it. defer inside the loop body runs at the end of each pass, so each word is freed before the next one is made.
Advanced
Section titled “Advanced”16. Clean up on failure
Section titled “16. Clean up on failure”Buffers.init allocates two buffers. If the second allocation fails, the first one leaks. Fix it, and write a test that proves it, using std.testing.FailingAllocator to make the second allocation fail. Practises Zig Errdefer and Zig Testing Allocator.
const Buffers = struct { input: []u8, output: []u8,
fn init(gpa: std.mem.Allocator, size: usize) !Buffers { const input = try gpa.alloc(u8, size); const output = try gpa.alloc(u8, size); return .{ .input = input, .output = output }; }};Hint: errdefer runs only when the function returns an error (the errdefer section of the language reference has a longer example). FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }) lets the first allocation through and fails the second.
Show solution
const std = @import("std");
const Buffers = struct { input: []u8, output: []u8,
fn init(gpa: std.mem.Allocator, size: usize) !Buffers { const input = try gpa.alloc(u8, size); errdefer gpa.free(input); const output = try gpa.alloc(u8, size); return .{ .input = input, .output = output }; }
fn deinit(self: Buffers, gpa: std.mem.Allocator) void { gpa.free(self.input); gpa.free(self.output); }};
test "init works" { const b = try Buffers.init(std.testing.allocator, 16); defer b.deinit(std.testing.allocator); try std.testing.expectEqual(16, b.output.len);}
test "no leak when the second allocation fails" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); try std.testing.expectError(error.OutOfMemory, Buffers.init(failing.allocator(), 16));}Output:
1/2 main.test.init works...OK2/2 main.test.no leak when the second allocation fails...OKAll 2 tests passed.Run it with zig test main.zig. Without the errdefer line, the second test still “passes”, but the testing allocator reports 1 tests leaked memory. and the run fails. The errdefer goes right after the allocation it protects, the same way defer does.
17. A generic largest
Section titled “17. A generic largest”Write largest(comptime T: type, items: []const T) ?T that returns the biggest item, or null for an empty slice. Test it with i32, f64 and an empty u8 slice. Practises Zig Generic Functions.
Hint: start with items[0] and loop over items[1..]. {?d} prints an optional number, or null.
Show solution
const std = @import("std");
fn largest(comptime T: type, items: []const T) ?T { if (items.len == 0) return null; var best = items[0]; for (items[1..]) |x| { if (x > best) best = x; } return best;}
pub fn main() void { const ints = [_]i32{ 3, -7, 12, 5 }; const floats = [_]f64{ 0.5, 2.25, 1.0 }; const empty = [_]u8{}; std.debug.print("{?d}\n", .{largest(i32, &ints)}); std.debug.print("{?d}\n", .{largest(f64, &floats)}); std.debug.print("{?d}\n", .{largest(u8, &empty)});}Output:
122.25nullZig makes a separate copy of largest for each T you use, while compiling. Try largest(bool, ...): it fails to build, because > doesn’t work on bool. The error appears at compile time, not when the program runs.
18. A generic stack
Section titled “18. A generic stack”Write fn Stack(comptime T: type) type that returns a struct with push, pop (returns ?T) and deinit, built on an ArrayList. Push three strings and pop them all. Practises Zig Generic Data Structures.
Hint: inside the returned struct, const Self = @This(); names the struct. ArrayList already has a pop that returns an optional.
Show solution
const std = @import("std");
fn Stack(comptime T: type) type { return struct { items: std.ArrayList(T) = .empty,
const Self = @This();
fn push(self: *Self, gpa: std.mem.Allocator, value: T) !void { try self.items.append(gpa, value); }
fn pop(self: *Self) ?T { return self.items.pop(); }
fn deinit(self: *Self, gpa: std.mem.Allocator) void { self.items.deinit(gpa); } };}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var stack: Stack([]const u8) = .{}; defer stack.deinit(gpa);
try stack.push(gpa, "first"); try stack.push(gpa, "second"); try stack.push(gpa, "third");
while (stack.pop()) |item| { std.debug.print("{s}\n", .{item}); }}Output:
thirdsecondfirstThe stack doesn’t store an allocator. It takes one in each method that needs it, like the standard library’s own containers do in 0.17. while (stack.pop()) |item| keeps going until pop returns null.
19. A table built while compiling
Section titled “19. A table built while compiling”Build a table of the squares of 0 to 9 at compile time, as a top-level constant, and print it. Practises Zig Comptime and Zig Blocks.
Hint: a top-level const is always worked out at compile time. Use a labeled block (blk: { ... break :blk table; }) to fill an array in a loop.
Show solution
const std = @import("std");
const squares = blk: { var table: [10]u32 = undefined; for (&table, 0..) |*slot, i| { slot.* = @intCast(i * i); } break :blk table;};
pub fn main() void { std.debug.print("{any}\n", .{squares}); std.debug.print("7 squared is {d}\n", .{squares[7]});}Output:
{ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 }7 squared is 49The loop runs inside the compiler. The finished program just contains the ten numbers, so there’s nothing left to compute at run time. for (&table, 0..) |*slot, i| gives a pointer to each element, so the loop can write into the array.
20. Print any struct
Section titled “20. Print any struct”Write describe(value: anytype) that prints every field of a struct as name = value, with strings in quotes. Try it on a Settings struct with default values. Practises Zig Reflection.
Hint: in Zig 0.17, @typeInfo(T).@"struct" has two lists that line up: field_names and field_types. Loop over both with inline for, and read each field with @field(value, name).
Show solution
const std = @import("std");
const Settings = struct { width: u32 = 80, height: u32 = 24, title: []const u8 = "untitled", fullscreen: bool = false,};
fn describe(value: anytype) void { const info = @typeInfo(@TypeOf(value)).@"struct"; inline for (info.field_names, info.field_types) |name, FieldType| { if (FieldType == []const u8) { std.debug.print("{s} = \"{s}\"\n", .{ name, @field(value, name) }); } else { std.debug.print("{s} = {any}\n", .{ name, @field(value, name) }); } }}
pub fn main() void { describe(Settings{ .title = "Snake", .fullscreen = true });}Output:
width = 80height = 24title = "Snake"fullscreen = trueinline for is needed because each field can have a different type, so the compiler writes out the loop body once per field. Older tutorials use info.fields with field.name: that’s the pre-0.17 form and doesn’t compile any more. The 0.17.0 release notes explain the change.
21. A stepping iterator
Section titled “21. A stepping iterator”Write a StepRange struct with a next() method that returns ?u32, counting from a start to an end (not included) in steps. Use it to print 0, 5, 10 and 15. Practises Zig Iterators.
Hint: next takes self: *StepRange because it changes the current position. Return null when you reach the end, and loop with while (it.next()) |n|.
Show solution
const std = @import("std");
const StepRange = struct { current: u32, end: u32, step: u32,
fn next(self: *StepRange) ?u32 { if (self.current >= self.end) return null; const value = self.current; self.current += self.step; return value; }};
pub fn main() void { var it: StepRange = .{ .current = 0, .end = 20, .step = 5 }; while (it.next()) |n| { std.debug.print("{d}\n", .{n}); }}Output:
051015This is the same pattern the standard library uses for tokenizeScalar, splitScalar and map iterators: a struct that remembers where it is, and a next that returns null when it’s done.
22. Test a parser
Section titled “22. Test a parser”Write parseAge(text: []const u8) !u8 that parses a number and returns error.TooOld if it’s above 130. Write three tests: a normal age, text that isn’t a number, and a number that’s too big. Practises Zig Testing.
Hint: std.fmt.parseInt(u8, text, 10) already returns errors like error.InvalidCharacter and error.Overflow. Check errors in tests with std.testing.expectError.
Show solution
const std = @import("std");
fn parseAge(text: []const u8) !u8 { const age = try std.fmt.parseInt(u8, text, 10); if (age > 130) return error.TooOld; return age;}
test "parses a normal age" { try std.testing.expectEqual(42, try parseAge("42"));}
test "rejects text that is not a number" { try std.testing.expectError(error.InvalidCharacter, parseAge("abc"));}
test "rejects an age that is too big" { try std.testing.expectError(error.TooOld, parseAge("200")); try std.testing.expectError(error.Overflow, parseAge("300"));}Output:
1/3 main.test.parses a normal age...OK2/3 main.test.rejects text that is not a number...OK3/3 main.test.rejects an age that is too big...OKAll 3 tests passed.Notice the two different errors for “too big”: 200 fits in a u8, so your own check catches it. 300 doesn’t fit, so parseInt fails first with error.Overflow. A good test finds edges like that.
23. Add it up with threads
Section titled “23. Add it up with threads”Fill an array with the numbers 1 to 1000. Start 4 threads, give each a quarter of the array, and let each one write its partial sum into its own slot of a results array. Then print the parts and the total. Practises Zig Threads.
Hint: std.Thread.spawn(.{}, function, .{ args }) starts a thread and join() waits for it. Give each thread a pointer to its own result slot, so no two threads write to the same memory.
Show solution
const std = @import("std");
fn sumPart(part: []const u64, result: *u64) void { var total: u64 = 0; for (part) |n| total += n; result.* = total;}
pub fn main() !void { var numbers: [1000]u64 = undefined; for (&numbers, 1..) |*n, i| n.* = i;
var results: [4]u64 = undefined; var threads: [4]std.Thread = undefined; const chunk = numbers.len / 4;
for (&threads, 0..) |*t, i| { const part = numbers[i * chunk .. (i + 1) * chunk]; t.* = try std.Thread.spawn(.{}, sumPart, .{ part, &results[i] }); } for (threads) |t| t.join();
var total: u64 = 0; for (results, 0..) |r, i| { std.debug.print("part {d}: {d}\n", .{ i, r }); total += r; } std.debug.print("total: {d}\n", .{total});}Output:
part 0: 31375part 1: 93875part 2: 156375part 3: 218875total: 500500The output is always the same, even though the threads run in any order, because nothing is printed until every thread has been joined. Each thread only touches its own slot, so there’s no data race and no need for a mutex. (Summing 1000 numbers is far too little work to be worth threads. The point is the pattern.)
- Beginner exercises practise loops,
if/switch, slices, strings, optionals and the “no unused names” rules. - Intermediate exercises add error unions, struct methods, tagged unions,
ArrayList, hash maps, sorting, stdout and leak hunting. - Advanced exercises cover
errdeferwithFailingAllocator, generics, comptime tables, reflection, iterators, tests and threads. - Every solution was run on Zig 0.17.1. If you’re on another version, some names may differ: see Zig Upgrading.
- If one felt hard, reread the linked lesson and try again a day later. That’s how it sticks.
Next up: Zig Interview Questions, short questions and answers that check you can explain Zig, not just write it.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference (0.17.1): the full rules, for when an exercise makes you want the whole story.
- Zig standard library docs (0.17.1): every function you can use, like
std.mem.sortandstd.ascii.toUpper. - Ziglings: over a hundred small broken programs to fix, one idea at a time. Its main branch follows Zig’s development builds; for 0.17.1, use its
v0.17.0tag. - Zig samples: short official example programs to read and change.