While, loop, break and continue
While, loop, break and continue
A countdown repeats until no reminders remain. While checks a condition before each iteration; loop repeats until something exits it. Break exits the nearest loop, while continue skips the remainder of the current iteration and begins the next one.
Change the state that controls termination. A loop expression can return a value through break value, which is useful when searching until a result is found. Nested loops can use labels to identify the loop being exited. Do not confuse leaving a loop with returning from the entire function.
What you’ll learn
- Trace the condition and update of a terminating loop.
- Distinguish break, continue and a function return.
While, loop, break and continue in action
Remaining: 3, 2, 1
The condition allows values three, two and one.
Remaining: 3, 2, 1Condition false at 0
Each body execution subtracts one; when remaining becomes zero, while stops.
Condition false at 0Break returns Ready
The loop then immediately breaks with Ready, which becomes result.
Break returns Ready
Work through the Rust program
Save the complete source as main.rs in the Rust environment. No standard input is needed.
Rust 2024 · complete program
fn main() {
let mut remaining = 3;
while remaining > 0 {
println!("Remaining: {remaining}");
remaining -= 1;
}
let result = loop { break "Ready"; };
println!("{result}");
}Expected output
Remaining: 3
Remaining: 2
Remaining: 1
ReadyFollow the execution
The condition allows values three, two and one. Each body execution subtracts one; when remaining becomes zero, while stops. The loop then immediately breaks with Ready, which becomes result.
Try the complete program in the Rust compiler. For tests, Cargo commands and local files, use the specified local environment.
Try a small variation
Your task: What prints if remaining starts at zero?
Rust 2024 · complete program
fn main() {
let mut remaining = 3;
while remaining > 0 {
println!("Remaining: {remaining}");
remaining -= 1;
}
let result = loop { break "Ready"; };
println!("{result}");
}Worked answer
Only Ready prints. While checks the condition before entering its body, so the countdown has no iterations.
Mistakes and limits to recognize
Continue can cause an accidental infinite loop if it skips the update that would eventually make the condition false. Prefer a for loop for a known collection. Loops are control flow, not a guarantee of bounded execution time.
Check your understanding
Take the idea into your next program
Only Ready prints. While checks the condition before entering its body, so the countdown has no iterations. Continue can cause an accidental infinite loop if it skips the update that would eventually make the condition false.
Further reading: the official Rust Book on while, loop, break and continue.
Reaching the recap and completing the quizzes are separate milestones.