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.for loop do in Rust?for variable in range { } with ranges like 1..=3 to include 3.in and ranges [OK]let mut sum = 0;
for i in 1..4 {
sum += i;
}
println!("{}", sum);for i in 0..5
println!("{}", i);
}i % 2 == 0. for i in 2..10 { if i % 2 = 0 { println!("{}", i); } } uses assignment (=) instead of comparison (==). for i in 2..=10 { if i / 2 == 0 { println!("{}", i); } } uses division instead of modulo. for i in 2..=10 { if i % 2 != 0 { println!("{}", i); } } prints odd numbers.Pass the test and this pattern moves unknown