DEV Community

BC
BC

Posted on

FizzBuzz in Rust

FizzBuzz

For numbers from 1 to 30:

  • print "FizzBuzz" if number is divisible by 3 and 5
  • print "Fizz" if number is divisible by 3
  • print "Buzz" if number is divisible by 5

Solution 1: general loop

fn main() {
    let mut n = 0;
    while n <= 30 {
        if n % 3 == 0 && n % 5 == 0 {
            println!("FizzBuzz");
        } else if n % 3 == 0 {
            println!("Fizz");
        } else if n % 5 == 0 {
            println!("Buzz");
        } else {
            println!("{}", n);
        }
        n += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution 2: for_each + closure

fn main() {
    (1..=30).for_each(|x| {
        if x % 3 == 0 && x % 5 == 0 {
            println!("FizzBuzz");
        } else if x % 3 == 0 {
            println!("Fizz");
        } else if x % 5 == 0 {
            println!("Buzz");
        } else {
            println!("{}", x);
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)