while

The while keyword can be used to loop until a condition is met.

Let’s write the infamous FizzBuzz using a while loop.

  1. fn main() {
  2. // A counter variable
  3. let mut n = 1;
  4. // Loop while `n` is less than 101
  5. while n < 101 {
  6. if n % 15 == 0 {
  7. println!("fizzbuzz");
  8. } else if n % 3 == 0 {
  9. println!("fizz");
  10. } else if n % 5 == 0 {
  11. println!("buzz");
  12. } else {
  13. println!("{}", n);
  14. }
  15. // Increment counter
  16. n += 1;
  17. }
  18. }