For Loops in Zig

In this blog post we explore the use of the for loop in Zig.

Here is the relevant code:

const std = @import("std");

pub fn main() void {
    for (1..4) |i| {
        std.debug.print("i: {} ", .{i});
    }
    std.debug.print("\n", .{});

    const items = [_]i8{ -2, 0, 2 };

    for (items) |item| {
        std.debug.print("Item: {} ", .{item});
    }
    std.debug.print("\n", .{});

    for (items, 0..) |item, index| {
        std.debug.print("Index: {}, Item: {} ", .{ index, item });
    }
    std.debug.print("\n", .{});

    for (items) |item| {
        if (item == 0) break;
        std.debug.print("Item: {} ", .{item});
    }
    std.debug.print("\n", .{});
}

The program begins by iterating over a simple integer range from 1 to 3 (using the exclusive upper bound syntax 1..4) with a capture variable i, printing each value to illustrate basic numeric looping. Next, it defines a small fixed-size array of signed 8-bit integers containing the values -2, 0 and 2, then iterates over just the elements using for (items) |item|, printing each one to show how for can directly traverse array contents without needing an index. The following loop combines both elements and indices by using for (items, 0..) |item, index|, where the built-in range 0.. automatically provides consecutive indices starting from zero, allowing simultaneous access to both position and value. Finally, the program demonstrates early termination with a conditional break: it iterates over the same array again, but immediately exits the loop when it encounters the value 0, resulting in only the first element (-2) being printed.

Save the code as for.zig and execute it:

$ zig version
0.15.2
$ zig run for.zig
i: 1 i: 2 i: 3
Item: -2 Item: 0 Item: 2
Index: 0, Item: -2 Index: 1, Item: 0 Index: 2, Item: 2
Item: -2

Happy coding in Zig!