Zig For Loops
A for loop repeats a block once for each item in a sequence. A range such as 0..3 is a sequence of numbers, and a string literal is a sequence of bytes.
A for loop walks a range and leaves out the end
The range 0..3 hands the loop three numbers. The printed lines show the end number 3 never appears.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for (0..3) |i| {
try out.print("{d}\n", .{i});
}
}
A for loop walks the bytes of a string
A string literal is a sequence of bytes. The loop captures one byte at a time and prints it as a character.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for ("zig") |ch| {
try out.print("{c}\n", .{ch});
}
}
A for loop can add up a range
The range 1..5 gives 1, 2, 3, and 4. The loop adds each one to total.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var total: usize = 0;
for (1..5) |n| {
total += n;
}
try out.print("{d}\n", .{total});
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for ("code", 0..) |ch, i| {
try out.print("{d}: {c}\n", .{ i, ch });
}
}
Key points
- Sequence: for takes the sequence to walk through in parentheses.
- Capture: the name between the two vertical bars holds the current item on each run.
- Range: the range 0..3 gives 0, 1, and 2, so the end number is left out.
- Index: adding a second sequence 0.. beside the first gives a counter that starts at 0 for each item.
- Bytes: looping over a string literal gives its bytes one at a time, and each byte is a u8 value.
In this example, the loop walks the bytes of the string "code" together with a 0.. counter. Each run prints the counter i and the byte ch, so the letters come out numbered from 0 to 3.
Note
a for loop over a range needs no manual step line, unlike a while loop.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop runs for (0..4) and prints each captured number. What is the last number it prints?