← Back to Rust Course | Chapter 3: Control Flow | Lesson 3 of 7

The while Loop

while repeats a block of code only for as long as a condition stays true.

Basic while Loop

A while loop checks its boolean condition before each iteration and stops as soon as that condition becomes false. It is ideal when the number of iterations is not known ahead of time.

Example: Basic while Loop

markup
fn main() {
    let mut n = 3;
    while n > 0 {
        println!("{}", n);
        n -= 1;
    }
    println!("Liftoff!");
}

while with a Complex Condition

The condition in a while loop can combine multiple checks using logical operators like && and ||, letting the loop respond to several changing pieces of state.

Example: while with a Complex Condition

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

Accumulating with while

while loops are commonly used to accumulate a result across iterations, such as summing values, until some stopping condition is reached.

Example: Accumulating with while

markup
fn main() {
    let mut sum = 0;
    let mut i = 1;
    while i <= 5 {
        sum += i;
        i += 1;
    }
    println!("Sum 1 to 5: {}", sum);
}

Avoiding Infinite Loops

Because while relies entirely on its condition to know when to stop, it is your responsibility to make sure the loop body eventually makes that condition false. Forgetting this creates a program that runs forever.

Example: Avoiding Infinite Loops

markup
fn main() {
    let mut countdown = 3;
    while countdown != 0 {
        println!("{}...", countdown);
        countdown -= 1;
    }
    println!("Done!");
}
Common Mistakes
  1. Forgetting to update the loop's condition variable inside the body, causing an infinite loop.
  2. Using while where a for loop over a range or iterator would be clearer and less error-prone.
  3. Writing while (condition) with parentheses out of habit from other languages -- unnecessary in Rust.
Chapter Summary
  • while checks its condition before every iteration and stops as soon as it becomes false.
  • The loop body must update whatever the condition depends on, or the loop never ends.
  • while does not produce a value the way loop can with break value.
  • Prefer for over while when iterating a known range or collection -- it's safer and more idiomatic.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.