Rust FizzBuzz Function

pub fn fizz_buzz(n: i32) -> Vec<String> {
    let mut result = Vec::new();

    for i in 1..=n {
        if i % 3 == 0 && i % 5 == 0 {
            result.push("FizzBuzz".to_string());
        } else if i % 3 == 0 {
            result.push("Fizz".to_string());
        } else if i % 5 == 0 {
            result.push("Buzz".to_string());
        } else {
            result.push(i.to_string());
        }
    }

    result
}

fn main() {
    let n = 15; // Change this number to generate FizzBuzz sequence up to 'n'
    let fizz_buzz_sequence = fizz_buzz(n);

    for fb in fizz_buzz_sequence {
        println!("{}", fb);
    }
}

(Playground)

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 3.24s
     Running `target/debug/playground`

Hi and welcome to the Rust users forum. It looks like you have found the option to share code from the rust Playground here. Usually, you should use this with some code you wrote yourself and have questions about or need help with. If you do so, also make sure to add a problem description or question to your post.

Like this there is no problematic code and no question for anyone to react to. Feel free to come back to this forum with any actual problem or question you have and can't easily find the answer to. Meanwhile, have fun with the Rust programming language - cheers :slight_smile:

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.