Zig While Loops
A while loop repeats a block of code while its condition stays true. The loop stops as soon as the condition becomes false.
A while loop repeats until the condition turns false
The counter starts at 1 and grows by 1 on each run. The loop prints it while it stays at or below 3.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var i: i32 = 1;
while (i <= 3) {
try out.print("{d}\n", .{i});
i += 1;
}
}
The continue expression runs after each run
The step i += 1 sits after the colon, so it runs at the end of every run. The counter itself is printed inside the body, starting from 0.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var i: i32 = 0;
while (i < 3) : (i += 1) {
try out.print("{d}\n", .{i});
}
}
A while loop can build up a total
Each run adds the counter to total and then raises the counter. After the loop, total holds the sum of 1, 2, 3, and 4.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var n: i32 = 1;
var total: i32 = 0;
while (n <= 4) {
total += n;
n += 1;
}
try out.print("{d}\n", .{total});
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var n: i32 = 5;
while (n > 0) : (n -= 1) {
try out.print("{d}\n", .{n});
}
try out.print("go\n", .{});
}
Key points
- Condition: while tests its bool condition before every run of the block.
- Body: the body is the block of code that repeats.
- Counter: a var counter is a common way to control how many times the loop runs.
- Step: a line inside the loop must move the condition toward false, or the loop never ends.
- Continue expression: extra code written after a colon runs at the end of each run of the loop.
- Zero runs: if the condition is false at the very first test, the body never runs.
In this example, n starts at 5 and the body prints it on each run. The continue expression lowers n by 1 after each print, so the loop counts down to 1, stops when n reaches 0, and then prints go.
Note
unlike a for loop, a while loop does not count for you, so the counting step is your job.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop starts with i at 0 and runs while (i < 4), adding 1 to i inside the body. How many times does the body run?