While loops
Quick answer
while repeats its body as long as a boolean condition remains true. It checks the condition before each iteration, so a false initial condition means the body never runs. Use while when a changing state determines the number of repetitions.
Condition, body and progress
Identify the initial state, the condition that permits another step and the update that approaches termination. When the loop finishes normally, the condition has become false. Check boundary cases, especially a starting state that already meets the stopping condition.
fn main() { let mut left = 3; while left > 0 { println!("{left}"); left -= 1; } println!("Done");}Expected stdout (not executed):
321DoneThe body does not print zero because the condition is checked first.
fn main() { let mut remaining = 0; while remaining > 0 { remaining -= 1; } println!("Left: {remaining}");}Expected stdout (not executed):
Left: 0The starting condition is false, so no subtraction occurs.
Common mistake
Forgetting the update can prevent termination. Also avoid subtracting from an unsigned zero; choose a condition that keeps the update in range.
Try it yourself
Start with 12 units and subtract three while the count is positive. How many iterations occur?
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
While loops — practice quiz
Choose one answer per question, then review the explanation.
What does `let mut n = 4; while n > 1 { n -= 1; }` leave in n?
If `while count < 5` starts with count=5, how many times does the body run?
In a countdown `while left > 0`, which body update approaches termination?