For loops and ranges
For loops and ranges
A teacher wants to total several marks without writing the same addition for each one. A for loop visits values from an iterator, which is a source of successive items. You can loop over an array or generate numbers from a range.
1..4 includes one, two and three; 1..=4 also includes four. Looping directly over values avoids manually managing indexes. enumerate adds a zero-based position when the report needs one. The accumulator must be mutable because each iteration changes it.
What you’ll learn
- Trace an accumulator through every mark.
- Distinguish included and excluded range endpoints.
For loops and ranges in action
Total: 0 → 70
Total changes from zero to 70, then 150, then 240.
Total: 0 → 70Total: 150 → 240
The range subsequently yields one, two and three.
Total: 150 → 240Days yielded: 1, 2, 3
The printed day number comes from each yielded value, not from an automatically maintained global counter.
Days yielded: 1, 2, 3
Work through the Rust program
Save the complete source as main.rs in the Rust environment. No standard input is needed.
Rust 2024 · complete program
fn main() {
let marks = [70, 80, 90];
let mut total = 0;
for mark in marks { total += mark; }
println!("Total: {total}");
for day in 1..=3 { println!("Day {day}"); }
}Expected output
Total: 240
Day 1
Day 2
Day 3Follow the execution
Total changes from zero to 70, then 150, then 240. The range subsequently yields one, two and three. The printed day number comes from each yielded value, not from an automatically maintained global counter.
Try the complete program in the Rust compiler. For tests, Cargo commands and local files, use the specified local environment.
Try a small variation
Your task: How many days print if the range becomes 1..3?
Rust 2024 · complete program
fn main() {
let marks = [70, 80, 90];
let mut total = 0;
for mark in marks { total += mark; }
println!("Total: {total}");
for day in 1..=3 { println!("Day {day}"); }
}Worked answer
Two days print: one and two. The upper endpoint is excluded by .., so day three is not yielded.
Mistakes and limits to recognize
A range does not automatically work backward; use a reversible iterator such as (1..=3).rev(). Moving a non-Copy collection into a loop consumes it, while iterating over a reference can borrow it. We will inspect that distinction in ownership lessons.
Check your understanding
Take the idea into your next program
Two days print: one and two. The upper endpoint is excluded by .., so day three is not yielded. A range does not automatically work backward; use a reversible iterator such as (1..=3).rev().
Further reading: the official Rust Book on for loops and ranges.
Reaching the recap and completing the quizzes are separate milestones.