TExcelTAD
Home › Zig › Zig Exercises

Zig Exercises

Time to practise what you've learned. Every exercise has a starter playground that already compiles and runs — the parts you need to write are marked TODO. Edit the code, press ▶ Run and compare with the expected result in the task description. Try on your own before opening the solution.

Tip: The output block under each starter shows what the unfinished starter prints. Zig rejects unused variables and parameters, so starters sometimes contain _ = name; lines — delete them once you use the name.

Exercise 1: Temperature table

Print Celsius values 0, 20, 40, 60, 80, 100 with their Fahrenheit equivalent (F = C * 9 / 5 + 32), formatted as 40 C = 104.0 F (Celsius right-aligned in 4 columns, Fahrenheit with one decimal in 6 columns).

zig · try it yourself
const std = @import("std");

pub fn main() void {
    std.debug.print("Celsius to Fahrenheit\n", .{});
    // TODO: loop over 0, 20, ..., 100 and print each line
}
Celsius to Fahrenheit
Show solution
zig
const std = @import("std");

pub fn main() void {
    std.debug.print("Celsius to Fahrenheit\n", .{});
    var c: u32 = 0;
    while (c <= 100) : (c += 20) {
        const f = @as(f64, @floatFromInt(c)) * 9.0 / 5.0 + 32.0;
        std.debug.print("{d:>4} C = {d:>6.1} F\n", .{ c, f });
    }
}

A while with a continue expression gives the step of 20. The integer is converted to f64 before multiplying so no precision is lost.

Exercise 2: FizzBuzz with switch

For 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, otherwise the number. Use a switch on a tuple-like value: hint — switch on @as(u2, @intFromBool(i % 3 == 0)) * 2 + @intFromBool(i % 5 == 0).

zig · try it yourself
const std = @import("std");

pub fn main() void {
    for (1..16) |i| {
        // TODO: print Fizz, Buzz, FizzBuzz or the number
        std.debug.print("{d} ", .{i});
    }
    std.debug.print("\n", .{});
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
zig
const std = @import("std");

pub fn main() void {
    for (1..16) |i| {
        const code = @as(u2, @intFromBool(i % 3 == 0)) * 2 + @intFromBool(i % 5 == 0);
        switch (code) {
            3 => std.debug.print("FizzBuzz ", .{}),
            2 => std.debug.print("Fizz ", .{}),
            1 => std.debug.print("Buzz ", .{}),
            0 => std.debug.print("{d} ", .{i}),
        }
    }
    std.debug.print("\n", .{});
}

Because code is a u2, it has exactly four possible values, so the switch is exhaustive without an else.

Exercise 3: Reverse a string in place

Write reverse(s: []u8) that reverses the bytes of a mutable slice using two indexes moving towards each other (don't use std.mem.reverse). Expected output: !gizgnizama.

zig · try it yourself
const std = @import("std");

fn reverse(s: []u8) void {
    // TODO: swap s[i] and s[j] while i < j
    _ = s;
}

pub fn main() void {
    var text = "amazingzig!".*; // copy the literal into a mutable array
    reverse(&text);
    std.debug.print("{s}\n", .{text});
}
amazingzig!
Show solution
zig
const std = @import("std");

fn reverse(s: []u8) void {
    if (s.len < 2) return;
    var i: usize = 0;
    var j: usize = s.len - 1;
    while (i < j) : ({
        i += 1;
        j -= 1;
    }) {
        const tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }
}

pub fn main() void {
    var text = "amazingzig!".*;
    reverse(&text);
    std.debug.print("{s}\n", .{text});
}

"…".* dereferences the pointer-to-array literal, copying it into a mutable array. The early return avoids s.len - 1 underflowing for an empty slice.

Exercise 4: Safe division

Write divide(a: i32, b: i32) !i32 that returns error.DivisionByZero when b is 0 and @divTrunc(a, b) otherwise. In main, print each result or the error name. Expected:

text
20 / 4 = 5
7 / 0 = error DivisionByZero
-9 / 2 = -4
zig · try it yourself
const std = @import("std");

fn divide(a: i32, b: i32) !i32 {
    // TODO: return an error for b == 0
    _ = b;
    return a;
}

pub fn main() void {
    const pairs = [_][2]i32{ .{ 20, 4 }, .{ 7, 0 }, .{ -9, 2 } };
    for (pairs) |p| {
        const result = divide(p[0], p[1]) catch |err| {
            std.debug.print("{d} / {d} = error {t}\n", .{ p[0], p[1], err });
            continue;
        };
        std.debug.print("{d} / {d} = {d}\n", .{ p[0], p[1], result });
    }
}
20 / 4 = 20
7 / 0 = 7
-9 / 2 = -9
Show solution
zig
fn divide(a: i32, b: i32) !i32 {
    if (b == 0) return error.DivisionByZero;
    return @divTrunc(a, b);
}

The error set is inferred from the return error.DivisionByZero statement. @divTrunc is required because the operands are signed.

Exercise 5: Find the longest word

Write longest(text: []const u8) ?[]const u8 that returns the longest word (split by spaces), or null for text with no words. On ties keep the first. Expected: longest: "subterranean" and longest: null.

zig · try it yourself
const std = @import("std");

fn longest(text: []const u8) ?[]const u8 {
    // TODO: tokenize by ' ' and remember the longest word
    _ = text;
    return null;
}

pub fn main() void {
    const samples = [_][]const u8{ "the subterranean river flows", "   " };
    for (samples) |s| {
        if (longest(s)) |w| {
            std.debug.print("longest: \"{s}\"\n", .{w});
        } else {
            std.debug.print("longest: null\n", .{});
        }
    }
}
longest: null
longest: null
Show solution
zig
fn longest(text: []const u8) ?[]const u8 {
    var best: ?[]const u8 = null;
    var words = std.mem.tokenizeScalar(u8, text, ' ');
    while (words.next()) |w| {
        if (best == null or w.len > best.?.len) best = w;
    }
    return best;
}

The returned slice points into the original text, so no allocation is needed.

Exercise 6: A struct with methods

Complete the Inventory struct: add(name, qty) stores up to 4 items in a fixed array, and total() returns the sum of all quantities. Expected output: 3 items, 42 units.

zig · try it yourself
const std = @import("std");

const Item = struct { name: []const u8, qty: u32 };

const Inventory = struct {
    items: [4]Item = undefined,
    len: usize = 0,

    fn add(self: *Inventory, name: []const u8, qty: u32) !void {
        // TODO: return error.Full when there are already 4 items
        _ = self;
        _ = name;
        _ = qty;
    }

    fn total(self: Inventory) u32 {
        // TODO: sum the quantities of the stored items
        _ = self;
        return 0;
    }
};

pub fn main() !void {
    var inv = Inventory{};
    try inv.add("screws", 30);
    try inv.add("hinges", 8);
    try inv.add("handles", 4);
    std.debug.print("{d} items, {d} units\n", .{ inv.len, inv.total() });
}
0 items, 0 units
Show solution
zig
fn add(self: *Inventory, name: []const u8, qty: u32) !void {
    if (self.len == self.items.len) return error.Full;
    self.items[self.len] = .{ .name = name, .qty = qty };
    self.len += 1;
}

fn total(self: Inventory) u32 {
    var sum: u32 = 0;
    for (self.items[0..self.len]) |item| sum += item.qty;
    return sum;
}

Only the first len elements are initialised, so total loops over the slice items[0..len] — never over the undefined rest.

Exercise 7: Tagged union calculator

Complete apply so each Op changes the accumulator: add adds, mul multiplies, reset sets it to 0. Expected output: result: 35.

zig · try it yourself
const std = @import("std");

const Op = union(enum) {
    add: i64,
    mul: i64,
    reset,
};

fn apply(acc: i64, op: Op) i64 {
    // TODO: switch on op
    _ = op;
    return acc;
}

pub fn main() void {
    const program = [_]Op{ .{ .add = 4 }, .{ .mul = 10 }, .reset, .{ .add = 5 }, .{ .mul = 7 } };
    var acc: i64 = 0;
    for (program) |op| acc = apply(acc, op);
    std.debug.print("result: {d}\n", .{acc});
}
result: 0
Show solution
zig
fn apply(acc: i64, op: Op) i64 {
    return switch (op) {
        .add => |n| acc + n,
        .mul => |n| acc * n,
        .reset => 0,
    };
}

Each branch captures the payload of its variant; reset has no payload. (4 × 10 = 40, reset to 0, then (0 + 5) × 7 = 35.)

Exercise 8: Word frequency with an ArrayList

Using an arena allocator and std.ArrayList([]const u8), collect the distinct words of the sentence in order of first appearance and print them with their counts. Expected:

text
to: 2
be: 2
or: 1
not: 1
4 distinct words
zig · try it yourself
const std = @import("std");

pub fn main() !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var words: std.ArrayList([]const u8) = .empty;
    defer words.deinit(allocator);
    var counts: std.ArrayList(u32) = .empty;
    defer counts.deinit(allocator);

    var it = std.mem.tokenizeScalar(u8, "to be or not to be", ' ');
    while (it.next()) |w| {
        // TODO: if w is already in `words`, increment its count; otherwise append it with count 1
        _ = w;
    }

    for (words.items, counts.items) |w, c| std.debug.print("{s}: {d}\n", .{ w, c });
    std.debug.print("{d} distinct words\n", .{words.items.len});
}
0 distinct words
Show solution
zig
while (it.next()) |w| {
    for (words.items, 0..) |existing, i| {
        if (std.mem.eql(u8, existing, w)) {
            counts.items[i] += 1;
            break;
        }
    } else {
        try words.append(allocator, w);
        try counts.append(allocator, 1);
    }
}

The for … else runs the else branch only when the loop did not break, i.e. when the word was not found. (With an arena the deinit calls are not strictly needed, but they keep the code correct if you switch to another allocator.) For large inputs a StringHashMap would be faster, but this keeps the order of first appearance for free.

Exercise 9: Generic maximum

Write a generic maxOf(comptime T: type, items: []const T) ?T that returns the largest item or null for an empty slice. Expected output: 9 2.5 null.

zig · try it yourself
const std = @import("std");

fn maxOf(comptime T: type, items: []const T) ?T {
    // TODO
    _ = items;
    return null;
}

pub fn main() void {
    const a = maxOf(u8, &.{ 3, 9, 4 });
    const b = maxOf(f32, &.{ -1.0, 2.5, 0.5 });
    const c = maxOf(i64, &.{});
    std.debug.print("{?d} {?d} {?d}\n", .{ a, b, c });
}
null null null
Show solution
zig
fn maxOf(comptime T: type, items: []const T) ?T {
    if (items.len == 0) return null;
    var best = items[0];
    for (items[1..]) |x| best = @max(best, x);
    return best;
}

@max works with any integer or float type, so the same body serves every T.

Test yourself

What does "abc".* produce?

  1. A pointer
  2. A copy of the literal as a [3:0]u8 array value
  3. The first character
  4. A slice

In a for … else loop, when does the else branch run?

  1. On every iteration
  2. When the loop finished without break
  3. When the loop broke early
  4. Never