Control Flow
For Loops
Summing a Range
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}");
}
total ← 0
1fn main() {2 let mut tota→ 0l = 0;3 for n in 1..=3 {total ← 1
pass 1 of 32let mut total = 0;3for 1n in 1..=3 {4 tota→ 1l += 1n;5}All 3 passes — pass 1 is the card above pass ntotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 println!("{total}");
5 }6 println!("{total}");7}output6
Follow the Loop
totalstarts at0.- The loop visits
n = 1, sototalbecomes1. - Then it visits
n = 2, sototalbecomes3. - Then it visits
n = 3, sototalbecomes6. - 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.