rust / beginner
Snippet
Using while Loops
While loops execute as long as a condition is true. They require manual counter updates unlike for loops. The example shows iterating through an array using an index variable with a while loop.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {let mut counter = 0;while counter < 3 {println!("Counter: {}", counter);counter += 1;}let numbers = [10, 20, 30, 40, 50];let mut index = 0;while index < numbers.len() {println!("Number at {}: {}", index, numbers[index]);index += 1;}}
Breakdown
1
while counter < 3
Loop runs while counter is less than 3
2
while index < numbers.len()
Iterates using index until reaching array length