CodeBlanks Logo Icon CodeBlanks

for loop

Iterate over an iterator with for.

The for loop

for yields every element of an iterator in turn; it is the most common loop in Rust. Ranges: 0..5 (excluding 5), 1..=5 (including 5):

for i in 1..=3 {
    print!("{i} ");
}
for meyve in ["elma", "armut"] {
    println!("{meyve}");
}
for i in (1..=3).rev() {   // 3 2 1
    print!("{i} ");
}

Index and value

To get the position together with the element, enumerate is used; step_by skips steps:

let isimler = ["Ada", "Can", "Ece"];
for (i, ad) in isimler.iter().enumerate() {
    println!("{}. {}", i + 1, ad);
}
for n in (0..=10).step_by(5) {   // 0 5 10
    print!("{n} ");
}

Practice Numbered list

Walk the array let gorevler = ["kod yaz", "test et", "yayınla"]; with .iter().enumerate() and print each line as 1. kod yaz.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let gorevler = ["kod yaz", "test et", "yayınla"];
    for (i, g) in gorevler.iter().enumerate() {
        println!("{}. {}", i + 1, g);
    }
}

Expected output

1. kod yaz
2. test et
3. yayınla

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which values does <code>for i in 0..3</code> give?

  • 3, 2, 1
  • 0, 1, 2 Correct answer
  • 0, 1, 2, 3
  • 1, 2, 3

Explanation: .. excludes the end; to include it, ..= is used.

2 Inclusive range

Question
for i in 1____10 {
    toplam += i;
}  // 1'den 10'a (dahil)
Answer
for i in 1..=10 {
    toplam += i;
}  // 1'den 10'a (dahil)

Explanation: ..= includes the end of the range too.

3 Expression and values

Term Meaning
0..3 0 1 2
1..=3 1 2 3
(1..=3).rev() 3 2 1
(0..=10).step_by(5) 0 5 10

All lessons in Beginner