0
0
Rustprogramming~5 mins

Loop execution flow in Rust

Choose your learning style9 modes available
Introduction

Loops help repeat actions many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you need to check every item in a list or collection.
When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a task until a certain condition is met.
Syntax
Rust
loop {
    // code to repeat
    if condition {
        break;
    }
}

loop creates an infinite loop unless you use break to stop it.

You can use continue to skip the rest of the current loop and start the next cycle.

Examples
This loop counts from 1 to 5 and then stops using break.
Rust
let mut count = 0;
loop {
    count += 1;
    println!("Count is {}", count);
    if count == 5 {
        break;
    }
}
This loop prints only odd numbers from 1 to 11 by skipping even numbers with continue.
Rust
let mut n = 0;
loop {
    n += 1;
    if n % 2 == 0 {
        continue; // skip even numbers
    }
    println!("Odd number: {}", n);
    if n > 10 {
        break;
    }
}
Sample Program

This program runs a loop that prints the current iteration number. When it reaches 3, it prints a message and stops the loop.

Rust
fn main() {
    let mut i = 1;
    loop {
        println!("Loop iteration: {}", i);
        if i == 3 {
            println!("Reached 3, stopping loop.");
            break;
        }
        i += 1;
    }
}
OutputSuccess
Important Notes

Use break to stop a loop when you want to exit early.

Use continue to skip the rest of the current loop cycle and start the next one.

Infinite loops can crash your program if you forget to use break.

Summary

Loops repeat code until you tell them to stop.

break stops the loop completely.

continue skips to the next loop cycle.