Skip to content

Repeat Work with for

The Course
•
25 min study

A week of study is not one session but many. You could bind each one to its own name and add them up by hand, but that breaks as soon as the number of sessions changes. Instead, keep the values together in a collection and let a loop visit each one.

The simplest collection is an array: a fixed number of values of one type, written between square brackets, such as [10, 25, 15]. A for loop runs its block once per item. Its loop variable, minutes below, names the current item for one pass through the block, called an iteration. To build a result across iterations, use an accumulator: a mutable binding created before the loop that each iteration updates.

Predict and run

Track total after each iteration. What will the program print?

Predict, then run Rust
fn main() {
    let durations = [10, 25, 15];
    let mut total = 0;
    for minutes in durations {
        total += minutes;
    }
    println!("Total: {total}");
}
Check your prediction
Text
Total: 50

total starts at 0, then becomes 10, 35 and finally 50. The println! sits after the loop's closing brace, so it runs once, after all three iterations. Replace the last value with 20 and predict the new total: the first two iterations behave as before, and only the last step changes, giving 55. Then move the println! inside the loop and predict the three lines it prints.

Where the accumulator lives

The position of let mut total = 0; decides what the loop computes. Here it is inside the loop body, so it is created fresh on every iteration:

Reset the total by mistake Rust
fn main() {
    let durations = [10, 25, 15];
    for minutes in durations {
        let mut total = 0;
        total += minutes;
        println!("Total so far: {total}");
    }
}
Text
Total so far: 10
Total so far: 25
Total so far: 15

Each iteration starts again from zero, so the "total" is just the current item. Worse, total disappears at the end of each iteration: a name exists only inside the braces where it was created, its scope. Printing it after the loop does not compile:

Rust
fn main() {
    for minutes in [10, 25, 15] {
        let mut total = 0;
        total += minutes;
    }
    println!("{total}");
}

The compiler reports error[E0425]: cannot find value total in this scope and helpfully adds that a binding with that name exists in a different scope. Create the accumulator before the loop, and it lives long enough to collect every item and be printed afterward.

Count with a range

Sometimes you want to repeat work a number of times rather than visit stored values. A range produces the numbers for you. 1..=3 includes both ends (1, 2, 3), while 1..3 stops before the end (1, 2). Arrays also know their length through .len().

Loop over a range of days Rust
fn main() {
    let durations = [30, 0, 45];
    println!("Planned days: {}", durations.len());
    for day in 1..=3 {
        println!("Day {day}");
    }
    for day in 1..3 {
        println!("Short week, day {day}");
    }
}
Text
Planned days: 3
Day 1
Day 2
Day 3
Short week, day 1
Short week, day 2

Forgetting the = is a classic off-by-one mistake: the loop quietly runs one time fewer than you meant. When a range has a boundary, run it and count the lines.

Loop over the data, not over positions

When you have an array, write for minutes in durations instead of counting positions with a range. There is no index to get wrong, and the loop automatically visits every item, however many there are.

Practice

Exercise

Your turn

Count how many sessions in [10, 20, 30, 5] meet a minimum of 20 minutes, and add up their minutes. Print Qualifying: 2 (50 min).

Your working space Rust
fn main() {
    let durations = [10, 20, 30, 5];
    println!("{durations:?}");
}
Hint 1: the idea

You need two accumulators. Change both only when the current item meets the minimum, so the if goes inside the loop.

Hint 2: a first step

Before the loop, create let mut count = 0; and let mut minutes_total = 0;. Inside, write if minutes >= 20 { ... }.

Worked solution
Run the solution Rust
fn main() {
    let durations = [10, 20, 30, 5];
    let mut count = 0;
    let mut minutes_total = 0;
    for minutes in durations {
        if minutes >= 20 {
            count += 1;
            minutes_total += minutes;
        }
    }
    println!("Qualifying: {count} ({minutes_total} min)");
}
Text
Qualifying: 2 (50 min)

The loop visits all four items, but only 20 and 30 pass the comparison. The 20 is the boundary: with > instead of >=, the count would drop to 1. In the next lesson you move the rule for a single session into its own function.

Was this article helpful?

Your response is saved on this device.