Introduction
A for loop helps you repeat actions easily without writing the same code many times.
A for loop helps you repeat actions easily without writing the same code many times.
for variable in collection { // code to repeat }
The variable takes each value from the collection one by one.
The collection can be a range, array, vector, or anything you can loop over.
1..5 means from 1 up to but not including 5.for i in 1..5 { println!("{}", i); }
let fruits = ["apple", "banana", "cherry"]; for fruit in fruits.iter() { println!("I like {}", fruit); }
for c in "hello".chars() { println!("{}", c); }
This program loops over the array numbers and prints each number with a label.
fn main() {
let numbers = [10, 20, 30];
for num in numbers.iter() {
println!("Number: {}", num);
}
}Rust's for loop provides each item by value from the collection (copies for Copy types), so you don't need to use indexes.
The range a..b includes a but excludes b. Use a..=b to include b.
Use a for loop to repeat actions over items in a collection.
The loop variable takes each item one by one.
Ranges and arrays are common collections to loop over.
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