For loops and ranges
Quick answer
A for loop visits items from an iterable value. A numeric range such as 1..4 provides 1, 2 and 3. Write 1..=4 when the endpoint must also be included. Ranges make simple counting loops concise without manually updating a counter.
Exclusive and inclusive endpoints
The syntax for item in range { ... } binds the current item for each iteration. A range with .. excludes the upper bound; ..= includes it when the range is nonempty. The loop variable is local to the loop body. Iterators and collections are explained in later chapters.
Expected stdout (not executed):
Step 1Step 2Step 3The exclusive upper bound keeps step 4 out of the sequence.
fn main() { let mut total = 0; for n in 1..=4 { total += n; } println!("Total: {total}");}Expected stdout (not executed):
Total: 10The sum includes four: 1 + 2 + 3 + 4.
Common mistake
0..5 gives five items, not six. Decide whether the endpoint is a limit or an item to include.
Try it yourself
Print the numbers from 2 through 6, then sum them using a mutable accumulator.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
For loops and ranges — practice quiz
Choose one answer per question, then review the explanation.
How many iterations occur in `for n in 3..6`?
What is total after `let mut total = 0; for n in 2..=5 { total += n; }`?
What happens in `for n in 4..4 { println!("{n}"); }`?