Loops and Iteration
LockedLesson 5 of 25 · Syntax · Easy
Finish these first:Conditionals and Branching →Or pass the tests below to unlock it now.
The big idea
A for loop in Rust steps cleanly through a range of numbers. Use 1..=3 when you want to include the ending number (1, 2, 3): Because coins changes on every pass of the loop, we mark it with let mut coins = 0;.
Think of it like this: Think of `1..=5` in Rust like saying 'count from 1 all the way through 5' — the `=` includes the last number.
Read the lesson
A for loop in Rust steps cleanly through a range of numbers.
Use 1..=3 when you want to include the ending number (1, 2, 3):
let mut coins = 0;
for i in 1..=3 {
coins += i; // coins becomes 6 (1 + 2 + 3)
}
Because coins changes on every pass of the loop, we mark it with let mut coins = 0;.
Quick check
Which numbers does `for i in 1..=5` step through in Rust?
Your challenge
Inside main(), use a for loop (for i in 1..=5) to add 1 through 5 into total (so total becomes 15).
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
Similar to python.loops (90% overlap). Iteration: for-of in JS, range-for in C++, single 'for' keyword in Go, Iterator/for-in in Rust.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Loops and Iteration.
Learn this first
- Conditionals and BranchingNot yet