By the end of this lesson
Repeat work with a clear stopping rule.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 7, or be comfortable explaining and running its examples.
Three words to know
- Iteration
- One repetition of a loop.
- Range
- A sequence of values such as 1..=3.
- Accumulator
- A variable updated to collect a result.
1. Understand the idea
for visits each item from an iterator. 1..=3 includes three, while 1..3 excludes it. A loop over a finite collection is easier to reason about than a loop without a clear stopping condition. Name the accumulator for what it measures, and check what should happen when there are no items. Avoid a loop that keeps retrying an operation forever.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
fn main() {
let mut total = 0;
for value in 1..=3 { total += value; }
println!("total={total}");
}
What you should see · example output
total=6
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
The accumulator starts at zero, then becomes 1, 3 and 6. The inclusive range produces exactly three items. Changing the range changes both the number of iterations and the sum; do not fix an expected output by guessing.
YOUR TURN
A small check before you continue
What does the same loop over 1..3 print?
Show a suggested answer
total=3 because the range yields only 1 and 2.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
