typestar

grade_report.zig in Zig

Quiz scores fold into averages and letter grades, then a formatted class report.

// Average quiz scores into letter grades and print the class report.
const std = @import("std");

const Student = struct {
    name: []const u8,
    quizzes: [3]u32,
};

const roster = [_]Student{
    .{ .name = "Imani", .quizzes = .{ 92, 88, 95 } },
    .{ .name = "Theo", .quizzes = .{ 78, 83, 80 } },
    .{ .name = "Sofia", .quizzes = .{ 85, 91, 89 } },
    .{ .name = "Miles", .quizzes = .{ 62, 70, 68 } },
};

fn average(quizzes: [3]u32) f32 {
    var sum: u32 = 0;
    for (quizzes) |q| sum += q;
    return @as(f32, @floatFromInt(sum)) / 3.0;
}

fn letter(avg: f32) []const u8 {
    if (avg >= 90.0) return "A";
    if (avg >= 80.0) return "B";
    if (avg >= 70.0) return "C";
    return "retake";
}

pub fn main() void {
    std.debug.print("student    avg  grade\n", .{});
    std.debug.print("---------------------\n", .{});

    var class_sum: f32 = 0;
    for (roster) |s| {
        const avg = average(s.quizzes);
        class_sum += avg;
        std.debug.print("{s:<8} {d:>5.1}  {s}\n", .{
            s.name, avg, letter(avg),
        });
    }

    std.debug.print("---------------------\n", .{});
    std.debug.print("class avg {d:.1}\n", .{class_sum / roster.len});
    std.debug.print("quizzes graded: {d}\n", .{roster.len * 3});
}

How it works

  1. The roster is an array of structs built with anonymous literal syntax.
  2. average sums a [3]u32 and @floatFromInt makes the division honest.
  3. {s:<8} and {d:>5.1} pad the columns; the footer averages the averages.

Keywords and builtins used here

The run, in numbers

Lines
45
Characters to type
1127
Tokens
385
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 355 seconds.

Type this snippet

Step 2 of 3 in Encore, step 26 of 27 in Language basics.

← Previous Next →