A for loop walks each value of a range or collection. Each pass can update accumulated state.

Program

Play the program to add the numbers 1 through 3.

loops.rs
Replay: real traced execution (multi-file project)
fn main() {
    let mut total = 0;
    for n in 1..=3 {
        total += n;
    }
    println!("{total}");
}
  1. total ← 0

    1fn main() {2    let mut tota→ 0l = 0;3    for n in 1..=3 {
  2. total ← 1

    pass 1 of 3
    2let mut total = 0;3for 1n in 1..=3 {4    tota→ 1l += 1n;5}
    All 3 passes — pass 1 is the card above
    passntotal
    110 1
    221 3
    333 6
  3. println!("{total}");

    5    }6    println!("{total}");7}
    output6

Follow the Loop

  1. total starts at 0.
  2. The loop visits n = 1, so total becomes 1.
  3. Then it visits n = 2, so total becomes 3.
  4. Then it visits n = 3, so total becomes 6.
  5. The program prints 6. | n | total after add | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 |
for `for n in 1..=3` repeats once per value.
inclusive range `1..=3` includes both endpoints.
compound assignment `total += n` adds into the accumulator.

Exercise: loops.rs

Reproduce the output 6, then identify the total after each visible loop value.