Library reference

Add the values in a list

Add every item once. Repeated values still count each time they occur.

for

Simple example

Add one, two and three.

Start1 · 2 · 3
Result6
lesson.zig
const std = @import("std");

pub fn main() !void {
    const values = [_]i64{1, 2, 3};
    var total: i64 = 0;
    for (values) |value| { total += value; }
    std.debug.print("{any}\n", .{total});
}
Output
6
Advertisements

Everyday examples

Add the three amounts on a receipt.

Start5 · 5 · 8
Result18
lesson.zig
const std = @import("std");

pub fn main() !void {
    const values = [_]i64{5, 5, 8};
    var total: i64 = 0;
    for (values) |value| { total += value; }
    std.debug.print("{any}\n", .{total});
}
Output
18

How many passengers boarded at the three stops?

Start2 · 7 · 1
Result10
lesson.zig
const std = @import("std");

pub fn main() !void {
    const values = [_]i64{2, 7, 1};
    var total: i64 = 0;
    for (values) |value| { total += value; }
    std.debug.print("{any}\n", .{total});
}
Output
10

How many exercise books arrived in three boxes?

Start10 · 8 · 9
Result27
lesson.zig
const std = @import("std");

pub fn main() !void {
    const values = [_]i64{10, 8, 9};
    var total: i64 = 0;
    for (values) |value| { total += value; }
    std.debug.print("{any}\n", .{total});
}
Output
27
Run the example
Terminal
zig run lesson.zig
Official documentation