0
0
Rustprogramming~5 mins

While loop in Rust

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves you from writing the same code many times.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to keep checking if a task is done before moving on.
When you want to repeat a game turn until the player wins or loses.
Syntax
Rust
while condition {
    // code to repeat
}

The condition is checked before each loop. If it is true, the code inside runs.

If the condition is false at the start, the code inside does not run at all.

Examples
This loop prints numbers 0, 1, and 2. It stops when count reaches 3.
Rust
let mut count = 0;
while count < 3 {
    println!("Count is {}", count);
    count += 1;
}
This loop keeps asking for user input until they type "exit".
Rust
let mut input = String::new();
while input.trim() != "exit" {
    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    println!("You typed: {}", input.trim());
}
Sample Program

This program counts down from 5 to 1, printing each number. After the loop ends, it prints "Blast off!".

Rust
fn main() {
    let mut number = 5;
    while number > 0 {
        println!("Countdown: {}", number);
        number -= 1;
    }
    println!("Blast off!");
}
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever.

You can change the variable inside the loop to control when it stops.

Summary

A while loop repeats code while a condition is true.

The condition is checked before each repetition.

Use it when you don't know how many times you need to repeat in advance.