0
0
Rustprogramming~5 mins

Loop with break in Rust

Choose your learning style9 modes available
Introduction

Loops let you repeat actions many times. Sometimes you want to stop the loop early when a condition is met. The break keyword helps you do that.

When you want to keep asking a user for input until they give a valid answer.
When searching through a list and stopping once you find what you need.
When running a game loop that ends when the player loses or wins.
When processing data until a certain condition is true.
When you want to exit an infinite loop safely.
Syntax
Rust
loop {
    // code to repeat
    if condition {
        break;
    }
}

The loop keyword creates an infinite loop.

The break keyword stops the loop immediately.

Examples
This prints "Hello" once and then stops the loop.
Rust
loop {
    println!("Hello");
    break;
}
This loop counts up to 3 but prints only 1 and 2 before breaking.
Rust
let mut count = 0;
loop {
    count += 1;
    if count == 3 {
        break;
    }
    println!("Count is {}", count);
}
Sample Program

This program prints numbers from 1 to 5. When the number reaches 5, the loop stops using break. Then it prints "Loop ended.".

Rust
fn main() {
    let mut number = 1;
    loop {
        println!("Number is {}", number);
        if number == 5 {
            break;
        }
        number += 1;
    }
    println!("Loop ended.");
}
OutputSuccess
Important Notes

You can use break inside any loop: loop, while, or for.

Using break helps avoid infinite loops when you want to stop early.

Summary

Loops repeat code.

break stops the loop immediately.

Use break to exit loops when a condition is met.