Zig, lesson 5
Zig has two loops. while repeats as long as a condition holds, and for walks over a range or
a collection. Both are deliberately simple, and both can stop early.
whileThe condition is checked before every pass. Make sure the body moves it towards false, or the
loop never ends.
For counting loops, while has an optional continue expression after a colon. It runs at the
end of every pass, which keeps the counter update next to the condition:
for over a range0..3 counts from 0 up to, but not including, 3. The value between bars, |i|, is the
: the current number, which is a . A loop can also walk over the items of
an array or slice, which you will see in the collections lesson.
2 exercises to try what you just read.
usizeforBecause the capture is a usize, mixing it with an i64 needs a conversion:
@as(i64, @intCast(i)). When you need a signed counter, a while loop with an i64 counter is
often simpler.
while can also unwrap an optional on every pass. This loop runs once per line and stops by
itself when takeDelimiter returns null at the end of the input:
break and continuebreak leaves the loop immediately.continue skips the rest of this pass. In a while with a continue expression, that
expression still runs, so the counter still moves on.A common pattern is a loop over the input that breaks as soon as it has found what it needs.
Read a whole number n and print its times table from 1 to 10, one line each, in this form:
Input: one line with n (it may be 0 or negative). Output: exactly ten lines.
You are saving up for a bike. Read your savings goal, then a list of deposits. Count how many deposits it takes for the total to reach the goal (equal counts as reached). Stop reading deposits as soon as you get there.
Input: the first line is the goal (at least 1). Each following line is one deposit (a whole number of 0 or more). There may be no deposits at all.
Output: if the goal is reached, print Goal reached! Deposits used: K. Otherwise print
Short by X. where X is how much is still missing.
prints Goal reached! Deposits used: 3
var balance: u64 = 100;
var years: u32 = 0;
while (balance < 200) {
balance += balance / 10;
years += 1;
}
try out.print("Doubled after {d} years\n", .{years});var i: i64 = 1;
while (i <= 3) : (i += 1) {
try out.print("Lap {d}\n", .{i});
}for (0..3) |i| {
try out.print("{d}\n", .{i}); // 0, 1, 2
}while (try in.takeDelimiter('\n')) |line| {
try out.print("You typed: {s}\n", .{line});
}var n: u32 = 0;
while (n < 100) : (n += 1) {
if (n % 2 == 1) continue; // skip odd numbers
if (n > 10) break; // stop completely after 10
try out.print("{d}\n", .{n});
}7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70100
30
50
40
10