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
fn main() {
let mut total = 0;
for n in 1..=3 {
total += n;
}
println!("{total}");
}
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.