← 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.
Syntax
rust
while condition {
    // body
}

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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `n`, initialized to `3`
    let mut n = 3;
    // Keep looping while `n > 0` holds
    while n > 0 {
        // Print "{}" to the console, substituting in `n` (with a trailing newline)
        println!("{}", n);
        n -= 1;
    }
    // Print "Liftoff!" to the console (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `x`, initialized to `0`
    let mut x = 0;
    // Declare a mutable variable `y`, initialized to `10`
    let mut y = 10;
    // Keep looping while `x < 5 && y > 0` holds
    while x < 5 && y > 0 {
        x += 1;
        y -= 2;
    }
    // Print "x = {}, y = {}" to the console, substituting in `x, y` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `sum`, initialized to `0`
    let mut sum = 0;
    // Declare a mutable variable `i`, initialized to `1`
    let mut i = 1;
    // Keep looping while `i <= 5` holds
    while i <= 5 {
        sum += i;
        i += 1;
    }
    // Print "Sum 1 to 5: {}" to the console, substituting in `sum` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `countdown`, initialized to `3`
    let mut countdown = 3;
    // Keep looping while `countdown != 0` holds
    while countdown != 0 {
        // Print "{}..." to the console, substituting in `countdown` (with a trailing newline)
        println!("{}...", countdown);
        countdown -= 1;
    }
    // Print "Done!" to the console (with a trailing newline)
    println!("Done!");
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.