Rust While Loop

Conditional repetition in Rust

⏰ What is a While Loop?

A while loop in Rust repeats code as long as a condition remains true. It's perfect when you don't know exactly how many times to repeat something.


// Basic while loop
let mut number = 1;

while number <= 3 {
    println!("Number: {}", number);
    number += 1;
}

println!("Done!");
                                    

Output:

Number: 1
Number: 2
Number: 3
Done!

While Loop Features

Condition Check

Tests condition before each iteration

while x > 0 {
    // runs while x is positive
    x -= 1;
}
🔄

Variable Updates

Update variables inside the loop

while count < 10 {
    count += 1;
    // do something
}
🛑

Early Exit

Use break to exit early

while true {
    if found {
        break;
    }
}
⏭️

Skip Iteration

Use continue to skip

while i < 10 {
    i += 1;
    if i % 2 == 0 {
        continue;
    }
}

🔹 Basic While Loop Syntax

While loops check a condition before each iteration:

fn main() {
    let mut countdown = 5;
    
    while countdown > 0 {
        println!("{}!", countdown);
        countdown -= 1;
    }
    
    println!("Liftoff! 🚀");
}

Output:

5!
4!
3!
2!
1!
Liftoff! 🚀

🔹 While with Complex Conditions

You can use complex boolean expressions:

fn main() {
    let mut x = 0;
    let mut y = 10;
    
    while x < 5 && y > 5 {
        println!("x: {}, y: {}", x, y);
        x += 1;
        y -= 2;
    }
    
    println!("Final: x={}, y={}", x, y);
}

Output:

x: 0, y: 10
x: 1, y: 8
x: 2, y: 6
Final: x=3, y=4

🔹 While with User Input Simulation

While loops are great for processing until a condition is met:

fn main() {
    let mut attempts = 0;
    let secret = 7;
    let guesses = [3, 5, 7]; // simulated user input
    let mut guess_index = 0;
    
    while guess_index < guesses.len() {
        let guess = guesses[guess_index];
        attempts += 1;
        
        println!("Attempt {}: Guessing {}", attempts, guess);
        
        if guess == secret {
            println!("Correct! Found it in {} attempts", attempts);
            break;
        } else {
            println!("Wrong guess, try again!");
        }
        
        guess_index += 1;
    }
}

Output:

Attempt 1: Guessing 3
Wrong guess, try again!
Attempt 2: Guessing 5
Wrong guess, try again!
Attempt 3: Guessing 7
Correct! Found it in 3 attempts

🔹 Avoiding Infinite Loops

Always ensure your condition can become false:

✅ Good Practice:

  • Always modify the condition variable inside the loop
  • Use a counter or limit to prevent infinite loops
  • Test your condition logic carefully

❌ Avoid:

  • Forgetting to update the condition variable
  • Using conditions that never become false
  • Complex conditions without clear exit paths
// Good: condition will eventually become false
let mut i = 0;
while i < 5 {
    println!("{}", i);
    i += 1; // ✅ i is updated
}

// Bad: infinite loop (don't do this!)
// while true {
//     println!("This runs forever!");
//     // ❌ no way to exit
// }

🧠 Test Your Knowledge

When does a while loop check its condition?