Lesson 4 of 15

Loops

Looping in Zig

Zig has two loop constructs: while and for. There is no C-style three-component for loop. Instead, Zig's loops are minimal and explicit.

While Loops

The while loop executes as long as its condition is true:

var i: u32 = 0;
while (i < 5) {
    std.debug.print("{}\n", .{i});
    i += 1;
}

While with Continue Expression

Zig's while has an optional continue expression that runs at the end of each iteration, similar to the post-statement in a C for loop:

var i: u32 = 0;
while (i < 5) : (i += 1) {
    std.debug.print("{}\n", .{i});
}

This is the idiomatic way to write a counting loop in Zig. The continue expression (i += 1) runs after each iteration, including when continue is used.

Loops gone wrong can feel like the TNG episode "Cause and Effect" --- the Enterprise stuck repeating the same disaster over and over. Always make sure your loop condition will eventually end!

For Loops

Zig's for loop iterates over slices and arrays. It does not count. If you want to count, use while:

const names = [_][]const u8{ "Alice", "Bob", "Charlie" };
for (names) |name| {
    std.debug.print("{s}\n", .{name});
}

You can also get the index:

for (names, 0..) |name, i| {
    std.debug.print("{}: {s}\n", .{ i, name });
}

Break and Continue

break exits the loop immediately. continue skips to the next iteration:

var i: u32 = 0;
while (i < 10) : (i += 1) {
    if (i == 5) break;
    if (i % 2 == 0) continue;
    std.debug.print("{}\n", .{i}); // prints 1, 3
}

Loops as Expressions

Like if, Zig loops can be expressions. A for or while loop with an else branch returns a value:

const target: u32 = 7;
var i: u32 = 0;
const result = while (i < 10) : (i += 1) {
    if (i == target) break i;
} else 0; // default if loop completes without breaking

Ranges with 0..n

You can iterate over a range by creating a range from a slice or using 0..n syntax with for:

for (0..5) |i| {
    std.debug.print("{}\n", .{i}); // prints 0 through 4
}

Your Task

Write a function fizzBuzz that takes a u32 parameter n and prints the numbers from 1 to n (inclusive), one per line, with these substitutions:

  • Print "FizzBuzz" if the number is divisible by both 3 and 5
  • Print "Fizz" if the number is divisible by 3
  • Print "Buzz" if the number is divisible by 5
  • Print the number otherwise
Zig runtime loading...
Loading...
Click "Run" to execute your code.