The while Loop
while repeats a block of code only for as long as a condition stays true.In this page:
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
// 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!");
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
Login to try C/C++/Java/PHP code in the editor
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
// 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!");
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to update the loop's condition variable inside the body, causing an infinite loop.
- Using
whilewhere aforloop over a range or iterator would be clearer and less error-prone. - Writing
while (condition)with parentheses out of habit from other languages -- unnecessary in Rust.
whilechecks 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.
whiledoes not produce a value the wayloopcan withbreak value.- Prefer
foroverwhilewhen 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: