What is a While Loop in Rust?
A while loop runs a block of code as long as its condition evaluates to true. The loop checks the condition before executing the code block, ensuring that the loop runs only when the condition is satisfied.
Syntax of While Loop
while condition {
// Code to execute
}
- condition: A boolean expression that determines whether the loop continues.
- The loop executes the code block repeatedly until the condition becomes false.
Key Features of While Loops
- Condition-Based Execution: The loop runs as long as the condition is true.
- Dynamic Iterations: Suitable when the number of iterations depends on runtime calculations.
- Pre-Test Loop: The condition is evaluated before executing the code block.
Example: Basic While Loop
fn main() {
let mut count = 1;
while count <= 5 {
println!("Count: {}", count);
count += 1;
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
- The loop starts with count = 1 and increments it in each iteration.
- When
count
exceeds 5, the condition count <= 5 becomes false and the loop stops.
Handling Infinite Loops with While
A while loop can unintentionally create an infinite loop if its condition is always true. You can use the break statement to exit the loop when necessary.
Example: Breaking an Infinite While Loop
fn main() {
let mut num = 0;
while true {
if num == 3 {
break;
}
println!("Number: {}", num);
num += 1;
}
}
Output:
Number: 0
Number: 1
Number: 2
- The break statement stops the loop when num equals 3.
Using While Loops with Collections
While loops are less commonly used for iterating over collections compared to for loops. However, they can still handle such scenarios with manual index management.
Example: Iterating Through an Array
fn main() {
let items = ["apple", "banana", "cherry"];
let mut index = 0;
while index < items.len() {
println!("Item: {}", items[index]);
index += 1;
}
}
Output:
Item: apple
Item: banana
Item: cherry
Example: While Loop with a User-Driven Condition
A while loop can depend on user input or other dynamic conditions.
fn main() {
let mut input = String::new();
let mut counter = 0;
while counter < 3 {
println!("Enter any word:");
std::io::stdin().read_line(&mut input).unwrap();
println!("You entered: {}", input.trim());
input.clear();
counter += 1;
}
}
Output:
This will prompt the user three times to enter a word and print it back.
While vs. For Loops in Rust
Feature | While Loop | For Loop |
---|---|---|
Condition-Based | Executes as long as the condition is true. | Iterates over a predefined sequence. |
Iteration Count | Dynamic and may depend on runtime conditions. | Fixed and determined by the sequence. |
Use Case | When the iteration count is unknown. | When the sequence or range is known. |
Using Continue in While Loops
The continue statement skips the remaining code in the current iteration and moves to the next iteration.
fn main() {
let mut num = 0;
while num < 5 {
num += 1;
if num % 2 == 0 {
continue;
}
println!("Odd Number: {}", num);
}
}
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
Nested While Loops
You can nest while loops to handle complex scenarios such as working with multi-dimensional data.
Example: Printing a Matrix
fn main() {
let mut i = 1;
while i <= 3 {
let mut j = 1;
while j <= 3 {
print!("{} ", i * j);
j += 1;
}
println!();
i += 1;
}
}
Output:
1 2 3
2 4 6
3 6 9