A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Fizz Buzz in Rust page! Here, you'll find the source code for this program as well as a description of how the program works.
fn main() {
for number in 1..101 {
if number % 3 == 0 && number % 5 == 0 {
println!("FizzBuzz");
} else if number % 3 == 0 {
println!("Fizz");
} else if number % 5 == 0 {
println!("Buzz");
} else {
println!("{}", number);
}
}
}
Fizz Buzz in Rust was written by:
This article was written by:
If you see anything you'd like to change or update, please consider contributing.
Before we dig into the code too much, let's take a look at the rules:
You can test for divisibility using the modulo operator %
. The modulo operator divides two numbers and yields the remainder, so i
modulo j
is 0
if i
is divisible by j
. In Rust, this is written as i % j
. Then, it's a simple matter of checking whether i % 3 == 0
or i % 5 == 0
.
In the very first line, we'll notice a for
-loop:
for number in 1..101
Here, we loop through all the numbers from 1 to 100.
From there, we begin our testing using an if statement:
if number % 3 == 0 && number % 5 == 0 {
println!("FizzBuzz");
} else if number % 3 == 0 {
println!("Fizz");
} else if number % 5 == 0 {
println!("Buzz");
} else {
println!("{}", number);
}
To run FizzBuzz in Rust, install the latest version of Rust. After that, create a project structure using cargo
:
cargo new fizz-buzz
Copy the code from Github into 'main.rs'. Compile and run the code from the command line using
cargo run main.rs
This will create a new 'target' directory containing the executable binary file.