Skip to content

Zig While

A loop runs the same code again and again, so you don’t have to copy it. Zig has two loops: for, for going through a list of things, and while, for repeating something as long as a condition stays true. This page is about while. It looks like C’s while, plus a neat extra slot for “what to do after each round” that replaces most of what C’s three-part for (;;) loop does.

while checks a condition. If it’s true, it runs the body, then checks again. It keeps going until the condition is false:

const std = @import("std");
pub fn main() void {
var count: u32 = 1;
while (count <= 3) {
std.debug.print("Round {d}\n", .{count});
count += 1;
}
std.debug.print("Done after {d}\n", .{count});
}

Output:

Round 1
Round 2
Round 3
Done after 4

count starts at 1. Each round prints it and adds 1. When count becomes 4, count <= 3 is false, and the loop ends. count is a var because the loop changes it. Like if, the condition must be a real bool: while (count) won’t compile.

Counting loops always have three parts: a start, a condition and a step. Zig gives the step its own slot, after the condition, written : (step). It’s called the continue expression, and it runs at the end of every round:

const std = @import("std");
pub fn main() void {
var i: u32 = 0;
while (i < 5) : (i += 1) {
std.debug.print("{d} ", .{i});
}
std.debug.print("\n", .{});
}

Output:

0 1 2 3 4

This is the same as C’s for (int i = 0; i < 5; i++), just spread over two lines. Why bother with a special slot when you could put i += 1 at the bottom of the body? Because of continue, which you’ll see next.

The step can be any statement, and you can put several in a block:

const std = @import("std");
pub fn main() void {
var i: u32 = 1;
var j: u32 = 1;
while (i * j < 100) : ({
i *= 2;
j *= 3;
}) {
std.debug.print("i={d} j={d} product={d}\n", .{ i, j, i * j });
}
}

Output:

i=1 j=1 product=1
i=2 j=3 product=6
i=4 j=9 product=36

Two keywords change what happens inside a loop:

  • break stops the loop right away.
  • continue skips the rest of this round and moves on to the next one.
const std = @import("std");
pub fn main() void {
var n: u32 = 0;
while (n < 10) : (n += 1) {
if (n % 2 == 0) continue;
if (n > 7) break;
std.debug.print("{d} ", .{n});
}
std.debug.print("\nstopped at {d}\n", .{n});
}

Output:

1 3 5 7
stopped at 9

Even numbers hit continue, so they’re skipped. Here’s why the continue expression matters: continue still runs : (n += 1). If you put n += 1 at the bottom of the body instead, continue would skip it, n would stay at 0 forever, and you’d have an infinite loop. When n reaches 9, break ends the loop. There’s more about both keywords, including breaking out of nested loops, in Zig Break/Continue.

Sometimes you don’t know the stopping point up front. Then you can write while (true) and break from inside when you’re done:

const std = @import("std");
pub fn main() void {
var balance: u32 = 1000;
var years: u32 = 0;
while (true) {
balance += balance / 10;
years += 1;
if (balance >= 2000) break;
}
std.debug.print("{d} years to reach {d}\n", .{ years, balance });
}

Output:

8 years to reach 2142

Each “year” adds 10% (using whole-number division, so it rounds down). The loop has no natural condition at the top, so the if ... break at the bottom decides when to stop.

Remember if (x) |value| from Zig If…Else? while can do the same thing with an optional (a value that might be null). It keeps looping as long as there’s a value, gives it to you as a capture, and stops at the first null.

This is how you go through an iterator in Zig. An iterator is a value with a next() method that returns the next item, or null when there are no more. Here std.mem.tokenizeScalar splits text into words at each space:

const std = @import("std");
pub fn main() void {
var words = std.mem.tokenizeScalar(u8, "apple banana cherry", ' ');
while (words.next()) |word| {
std.debug.print("word: {s}\n", .{word});
}
}

Output:

word: apple
word: banana
word: cherry

Each round calls words.next(). While it returns a word, the word is captured as word and the body runs. After "cherry", next() returns null and the loop stops. The double space between banana and cherry doesn’t produce an empty word, because tokenize skips empty pieces. words is a var because next() moves it forward each time.

You can write your own optional loop too. Here the variable becomes null to stop:

const std = @import("std");
pub fn main() void {
var countdown: ?u8 = 3;
while (countdown) |n| {
std.debug.print("{d}...\n", .{n});
countdown = if (n == 1) null else n - 1;
}
std.debug.print("Liftoff!\n", .{});
}

Output:

3...
2...
1...
Liftoff!

?u8 means “a u8 or null”. You’ll learn optionals properly in Zig Optionals. while can also loop over error unions with while (x) |value| { ... } else |err| { ... }; the language reference on while with error unions shows how, and it’ll make more sense after Zig Errors.

A while loop can have an else branch. It runs once, when the condition becomes false. If you leave the loop with break, the else is skipped. That makes it a clean way to answer “did I find it?”:

const std = @import("std");
pub fn main() void {
const numbers = [_]u32{ 4, 8, 15, 16, 23, 42 };
var i: usize = 0;
while (i < numbers.len) : (i += 1) {
if (numbers[i] > 20) {
std.debug.print("First number over 20 is at index {d}\n", .{i});
break;
}
} else {
std.debug.print("No number over 20\n", .{});
}
}

Output:

First number over 20 is at index 4

[_]u32{ ... } is an array of numbers, and numbers.len is how many there are (more in Zig Arrays). The loop finds 23 at index 4 and breaks, so the else doesn’t run. If no number were over 20, the loop would end on its own and the else would print “No number over 20”.

A loop can even produce a value. break value gives the value of the whole loop, and the else gives the value when there was no break:

const std = @import("std");
pub fn main() void {
const numbers = [_]u32{ 4, 8, 15, 16 };
var i: usize = 0;
const found: bool = while (i < numbers.len) : (i += 1) {
if (numbers[i] == 15) break true;
} else false;
std.debug.print("Contains 15: {}\n", .{found});
}

Output:

Contains 15: true

Read it as “loop through the numbers; if you hit 15, the answer is true; if you get to the end, the answer is false”. Python has a while ... else too, with the same “runs when there was no break” rule. Most other languages don’t.

Use a while loop with a continue expression to add up all the numbers from 1 to 100, then print the total.

Hint: start n at 1, loop while (n <= 100) : (n += 1), and add n to a total each round.

Show solution
const std = @import("std");
pub fn main() void {
var total: u32 = 0;
var n: u32 = 1;
while (n <= 100) : (n += 1) {
total += n;
}
std.debug.print("Total: {d}\n", .{total});
}

Output:

Total: 5050

The continue expression takes care of the step, so the body only has to do the adding.

Start with n = 6. While n isn’t 1: if it’s even, halve it; if it’s odd, set it to 3 * n + 1. Print each value and count how many steps it takes to reach 1.

Hint: while (n != 1), and inside an if (n % 2 == 0) ... else ....

Show solution
const std = @import("std");
pub fn main() void {
var n: u32 = 6;
var steps: u32 = 0;
while (n != 1) {
n = if (n % 2 == 0) n / 2 else 3 * n + 1;
steps += 1;
std.debug.print("{d} ", .{n});
}
std.debug.print("\n{d} steps\n", .{steps});
}

Output:

3 10 5 16 8 4 2 1
8 steps

An if expression picks the next value in one line. Nobody has proved this loop ends for every starting number, which is why it’s a famous puzzle.

This program is meant to print the odd numbers below 10, but it never finishes. Fix it without removing the continue.

const std = @import("std");
pub fn main() void {
var i: u32 = 0;
while (i < 10) {
if (i % 2 == 0) continue;
std.debug.print("{d} ", .{i});
i += 1;
}
std.debug.print("\n", .{});
}

Hint: what does continue skip when i is 0?

Show solution
const std = @import("std");
pub fn main() void {
var i: u32 = 0;
while (i < 10) : (i += 1) {
if (i % 2 == 0) continue;
std.debug.print("{d} ", .{i});
}
std.debug.print("\n", .{});
}

Output:

1 3 5 7 9

In the broken version, continue at i == 0 skips i += 1, so i stays 0 forever. Moving the step into the continue expression makes it run every round, even after continue.

  • while (condition) { ... } repeats the body as long as the condition is true. The condition must be a bool.
  • The continue expression while (i < n) : (i += 1) runs after every round, even after continue.
  • break stops the loop; continue skips to the next round.
  • while (x) |value| loops over an optional, and stops at the first null. That’s how you use iterators.
  • while ... else runs the else when the loop ends without break. With break value, the loop produces a value.

Next up: Zig For, the loop for going through arrays, slices and ranges of numbers.

Quick check

1. In while (i < 10) : (i += 1) { if (skip) continue; ... }, what happens to i when continue runs?
2. When does the else branch of a while loop run?
3. What does while (it.next()) |item| { ... } do?