Table of contents
Overview
The fizz buzz challenge is reportedly used as an interview screening device for computer programmers. The problem appears trivial yet it could turn out to be a hard nut to crack, especially for those learning a specific programming language. In this tutorial, I will show how to solve the Fizz Buzz challenge In Rust Lang
The Problem
- If a number is a multiple of 3, print Fizz instead of the number
- If a number is a multiple of 5, print Buzz instead of the number
- If a number is both multiple of 3 and 5, print FizzBuzz
- Else print the number
The Approach
As I shall show shortly, the key to solving the challenge is getting the precedence right,
- Printing
FizzBuzz
has the highest precedence, since it wraps around multiples of 5 and 3, thus it shall come first - Next, printing
Fizz
orBuzz
in place of 3 and 5 respectively has same precedence and it will be handled withconditionals (if, else if ....)
thus either can come immediately afterFizzBuzz
- Finally, printing the number that is neither a multiple of 3, of 5, nor of both comes last.
The Solution
The following steps assume you have some rust already installed on you computer, if not check out the installation guide
Crate a new project with
cargo
, rust's default package manager. To do this, run the following command in your terminal, This will create a new folder calledrust-fizz-buzz
cargo new rust-fizz-buzz --bin
Navigate to the
rust-fizz-buzz
folder and open it in your preferred text editor or IDE, you should see the following listings inrust-fizz-buzz/src/main.rs
fn main() { println!("Hello, world!"); }
Delete
println!("Hello, world!");
from themain.rs
file. Now we are set to solve the challenge.As mentioned in the approach, the key to the solution is getting the precedence right, for this reason, we'll take the once with highest precedence (FizzBuzz) way down to one with the least(the number). But first, let's begin by printing 1 - 100 which is the range of number we'll use.
fn main() { for number in 1..101{ println!("{}", number); } }
Note that the
1..101
is used to get the precise range (1 - 100) instead of1..100
which will return1 - 99
. Run the following command in therust-fizz-buzz
folder to verify, first with1..100
then1..101
.cargo run
Update the
main.rs
file with the following code.
fn main() {
for number in 1..101 {
//fizz buzz takes highest precedence, so it comes first
if number % 5 == 0 && number % 3 == 0 {
println!("fizz buzz");
} else if number % 5 == 0 {
println!("buzz");
} else if number % 3 == 0 {
println!("fizz");
} else {
println!("{}", number);
}
}
}
Run the following command, the rust-fizz-buzz
folder.
cargo run
If all goes well, you should get an output similar to this