The while Loop
while repeats a block of code only for as long as a condition stays true.In this page:
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
fn main() {
let mut n = 3;
while n > 0 {
println!("{}", n);
n -= 1;
}
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
fn main() {
let mut x = 0;
let mut y = 10;
while x < 5 && y > 0 {
x += 1;
y -= 2;
}
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
fn main() {
let mut sum = 0;
let mut i = 1;
while i <= 5 {
sum += i;
i += 1;
}
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
fn main() {
let mut countdown = 3;
while countdown != 0 {
println!("{}...", countdown);
countdown -= 1;
}
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: