Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import CodeBlock from "@theme/CodeBlock";

import For from "!!raw-loader!./05.for.zig";
import ForIndex from "!!raw-loader!./05.for-index.zig";
import ForMultipleIterables from "!!raw-loader!./05.for-multiple-iterables.zig";

# For loops

For loops are used to iterate over arrays (and other types, to be discussed
later). For loops follow this syntax. Like while, for loops can use `break` and
`continue`. Here, we've had to assign values to `_`, as Zig does not allow us to
have unused values.
later). Like while, for loops can use `break` and `continue`.

<CodeBlock language="zig">{For}</CodeBlock>

Iterating over multiple arrays is possible using a single for loop, as long as
all arrays are the same size.

<CodeBlock language="zig">{ForMultipleIterables}</CodeBlock>

To extract the index while iterating, use `0..` to indicate an unbounded range
starting at zero.

<CodeBlock language="zig">{ForIndex}</CodeBlock>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// hide-start
const expect = @import("std").testing.expect;

// hide-end
test "for" {
const vals = [4]u8{ 10, 20, 30, 40 };
var val_sum: u32 = 0;
var index_sum: usize = 0;
for (vals, 0..) |num, index| {
val_sum += num;
index_sum += index;
}
try expect(index_sum == 6);
try expect(val_sum == 100);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// hide-start
const expect = @import("std").testing.expect;

// hide-end
test "for loop with multiple iterables" {
var sum: i32 = 0;
const digits = [4]i32{ 7, 3, 4, 9 };
const places = [4]i32{ 1, 10, 100, 1000 };
for (digits, places) |digit, place| {
sum += digit * place;
}
try expect(sum == 9437);
}
28 changes: 14 additions & 14 deletions website/versioned_docs/version-0.14/01-language-basics/05.for.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@ const expect = @import("std").testing.expect;

// hide-end
test "for" {
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };

for (string, 0..) |character, index| {
_ = character;
_ = index;
}

for (string) |character| {
_ = character;
const vals = [_]u8{ 2, 3, 4 };
var sum: u8 = 0;
// num is the captured value on each iteration of the loop.
for (vals) |num| {
sum += num;
}
try expect(sum == 9);
}

for (string, 0..) |_, index| {
_ = index;
test "for-with-continue" {
const vals = [_]u8{ 2, 3, 0, 4 };
var product: u32 = 1;
for (vals) |num| {
if (num == 0) continue;
product *= num;
}

for (string) |_| {}
try expect(product == 24);
}