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.
A basic while loop
Section titled “A basic while loop”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 1Round 2Round 3Done after 4count 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.
The continue expression: : (i += 1)
Section titled “The continue expression: : (i += 1)”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 4This 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=1i=2 j=3 product=6i=4 j=9 product=36break and continue
Section titled “break and continue”Two keywords change what happens inside a loop:
breakstops the loop right away.continueskips 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 7stopped at 9Even 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.
while (true) and break
Section titled “while (true) and break”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 2142Each “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.
while with captures
Section titled “while with captures”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: appleword: bananaword: cherryEach 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.
while ... else
Section titled “while ... else”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: trueRead 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.
Practice
Section titled “Practice”1. Sum of 1 to 100
Section titled “1. Sum of 1 to 100”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: 5050The continue expression takes care of the step, so the body only has to do the adding.
2. Collatz steps
Section titled “2. Collatz steps”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 18 stepsAn 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.
3. Fix the frozen loop
Section titled “3. Fix the frozen loop”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 9In 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 abool.- The continue expression
while (i < n) : (i += 1)runs after every round, even aftercontinue. breakstops the loop;continueskips to the next round.while (x) |value|loops over an optional, and stops at the firstnull. That’s how you use iterators.while ... elseruns theelsewhen the loop ends withoutbreak. Withbreak value, the loop produces a value.
Next up: Zig For, the loop for going through arrays, slices and ranges of numbers.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: while: every form of
while, with break, continue, labels andelse. - Zig language reference: while with optionals: looping until
null, with examples. - Zig in-depth overview: the official tour of the language.
- Ziglings: hands-on exercises, with a few on
whileloops early on.