Concept Flow - For loop
Start
Get iterable
Take next item?
No→Exit loop
Yes
Execute loop body
Repeat: Take next item?
The for loop gets an iterable, takes each item one by one, runs the loop body, and stops when no items remain.
fn main() {
for i in 1..4 {
println!("{}", i);
}
}| Iteration | i value | Condition (next item?) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | Yes | Print 1 | 1 |
| 2 | 2 | Yes | Print 2 | 2 |
| 3 | 3 | Yes | Print 3 | 3 |
| 4 | - | No | Exit loop | - |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | - | 1 | 2 | 3 | - |
Rust for loop syntax:
for variable in iterable {
// code
}
Runs loop body once per item in iterable.
Ranges like 1..4 include start but exclude end.
Loop stops when no more items.