Loops in Rust



In this tutorial, we will learn about different types of loops in Rust. We will cover the basics of `loop`, `while`, and `for` loops.


What is a Loop

A loop is a control flow statement that allows code to be executed repeatedly based on a condition.

Loops

Rust supports three types of loops: `loop` loops, `while` loops, and `for` loops.

Loop

A `loop` is used to execute a block of code repeatedly until explicitly terminated. The syntax for the loop is:

loop {
    // Code block to be executed
    if condition {
        break;
    }
}

While Loop

A `while` loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:

while condition {
    // Code block to be executed
}

For Loop

A `for` loop is used when iterating over a collection or range of values. The syntax for the for loop is:

for item in collection_or_range {
    // Code block to be executed
}


Example 1: Printing Numbers from 1 to 5 using Loop

  1. Use a loop to print numbers from 1 to 5.

Rust Program

let mut i = 1;
loop {
    print!("{} ", i);
    i += 1;
    if i > 5 {
        break;
    }
}

Output

1 2 3 4 5 


Example 2: Printing Numbers from 1 to 3 using While Loop

  1. Declare a mutable integer variable i and initialize it to 1.
  2. Use a while loop to print numbers from 1 to 3.

Rust Program

let mut i = 1;
while i <= 3 {
    print!("{} ", i);
    i += 1;
}

Output

1 2 3 


Example 3: Printing Even Numbers from 2 to 10 using For Loop

  1. Use a for loop to print even numbers from 2 to 10.

Rust Program

for i in 2..=10 {
    if i % 2 == 0 {
        print!("{} ", i);
    }
}

Output

2 4 6 8 10