While Loops
A while repeats the loop body as long as a condition is
true:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
var i: u64 = 0;
while (i < 10)
i += 1;
print("i is {}\n", .{i});
}$ zig run while.zig
i is 10
We can use break to exit early and continue
to skip to the next iteration:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
var i: u64 = 0;
while (true) {
i += 1;
if (i == 10)
break;
if (i % 4 != 0)
continue;
print("{} is divisible by 4\n", .{i});
}
}$ zig run break-and-continue.zig
4 is divisible by 4
8 is divisible by 4
A while loop can contain a continue expression that runs before the loop continues:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
var i: u64 = 1;
while (i < 20) : (i += 1)
if (i % 6 == 0)
print("{} is divisible by 6\n", .{i});
}$ zig run continue-expr.zig
6 is divisible by 6
12 is divisible by 6
18 is divisible by 6
We can also use a while loop as an expression:
const std = @import("std");
const print = std.debug.print;
pub fn smallestCommonMultiple(a: u64, b: u64) u64 {
var i: u64 = 1;
return while (i < a * b) : (i += 1) {
if (i % a == 0 and i % b == 0)
break i; // break yields a result
} else a * b; // else yields the default result
}
pub fn main() void {
print("{}\n", .{smallestCommonMultiple(4, 6)});
}$ zig run loop-as-expr.zig
12
Next example: For Loops.