Code examples

Pack lunch bags

Integer division counts full groups. The remainder tells you what is left.

Simple example

Start7 ÷ 3
Result2 1
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    try show(@divFloor(7, 3));
    try show(@mod(7, 3));
}
Output
2
1
Advertisements

Everyday examples

You have 17 apples. Each lunch bag holds 5. Show the number of full bags, then the apples left over.

Start17 ÷ 5
Result3 2
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const apples: i64 = 17;
    const per_bag: i64 = 5;
    try show(@divFloor(apples, per_bag));
    try show(@mod(apples, per_bag));
}
Output
3
2
Run the example
Terminal
zig run lesson.zig
Official documentation