How to Solve a FizzBuzz Algorithm Problem
What is FizzBuzz?
FizzBuzz is a simple and popular programming problem, sometimes given in Software Developer coding interviews to test programming ability. The problem is set up like this:
Create a function (we’ll call it fizzBuzz) that will print numbers from 1 to 100, with certain exceptions:
- If the number is a multiple of 3, print “Fizz” instead of the number.
- If the number is a multiple of 5, print “Buzz” instead of the number.
- If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number.
Partial Example of fizzBuzz function output
fizzBuzz function with pseudocode👇🏾
function fizzBuzz(){
// multiple of 3 and 5, print “FizzBuzz”
// multiple of 3, print “Fizz”
// multiple of 5, print “Buzz”
}
Now let’s get to solving!
Step 1: Create a For Loop
For loops are used to repeat a section of code n times. A for loop serves our purpose perfectly because we want to print numbers from 1–100 with certain exceptions.
for (let i=1; i<=100; i++) {}
Step 2: Create IF…ELSE Statements
Step 2.1: Create An IF Statement For Multiples of 3 & 5
In our if statement we check to see if a given number(i) has a remainder of 0 when divided by both 3 & 5, this would make it a multiple and thus we would print “FizzBuzz”:
// multiple of 3 and 5, print “FizzBuzz”
if (i % 3 === 0 && i % 5 === 0){
console.log("FizzBuzz")
}
Step 2.2: Create An ELSE IF Statement For Multiples of 3
Now we will create our else if statement that will account for numbers that are multiples of 3 and print “Fizz”:
// multiple of 3, print “Fizz”
else if (i % 3 === 0){
console.log("Fizz")
}
Step 2.3: Create An ELSE IF Statement For Multiples of 5
We will create another else if statement that will account for numbers that are multiples of 5 and print “Buzz”:
// multiple of 5, print “Buzz”
else if (i % 5=== 0){
console.log("Buzz")
}
Step 2.4: Create An ELSE Statement For Multiples of Neither 3 Nor 5
We can’t forget numbers that aren’t multiple of 3 or 5, we will just print those numbers:
// multiple of neither 3 nor 5, print number
else{
console.log(i)
}
The Final Product
If you found this helpful, stay tuned for more articles where I’ll be solving common algorithm problems!😊🎉