Introduction
In this lab, we learn about the while keyword, which is used to create a loop that continues executing as long as a specified condition is true. To illustrate its usage, we write a program in Rust called FizzBuzz. The program uses a while loop to iterate through numbers from 1 to 100. Inside the loop, it checks if the current number is divisible by 3 and 5 (i.e., a multiple of 15) and prints "fizzbuzz" in such cases. If the number is only divisible by 3, it prints "fizz", and if it is only divisible by 5, it prints "buzz". For all other numbers, it simply prints the number itself. The loop continues until the counter variable reaches 101, incrementing it after printing each number or label.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
while
The while keyword can be used to run a loop while a condition is true.
Let's write the infamous FizzBuzz using a while loop.
fn main() {
// A counter variable
let mut n = 1;
// Loop while `n` is less than 101
while n < 101 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
// Increment counter
n += 1;
}
}
Summary
Congratulations! You have completed the While lab. You can practice more labs in LabEx to improve your skills.