DEV Community

FTWCougar
FTWCougar

Posted on

Solving FizzBuzz

Image of FizzBuzz


A common way to quickly assess a candidate's coding abilities is to use the well-known programming problem FizzBuzz. The objective is to create a program that prints the numbers from 1 to a specified number, but instead of printing the number for multiples of 3, it prints "Fizz," and for multiples of 5, it produces "Buzz." Print "FizzBuzz" when the given number is a multiple of both 3 and 5.

For example, the output of FizzBuzz for the numbers 1 to 15 would be:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Enter fullscreen mode Exit fullscreen mode

Here is a straightforward JavaScript version of FizzBuzz using an if statement:

for (let i = 1; i <= 100; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

Enter fullscreen mode Exit fullscreen mode

This program iterates through the numbers from 1 to 100 using a for loop. The loop outputs "FizzBuzz" if the current number is a multiple of 3 and 5 (checked using the modulo operator%). "Fizz" is printed if the number is only a multiple of 3. "Buzz" is printed if the number is just a multiple of 5. If the number is not a multiple of 3 or 5, it is printed as is.

Although this implementation is quite simple, there are a few considerations to keep in mind. The sequence of the if statements is crucial first. A number that is a multiple of both 3 and 5 should be regarded as a "FizzBuzz" rather than a "Fizz" or a "Buzz," so the check for "FizzBuzz" must come before the checks for "Fizz" and "Buzz."

Second, even though the else statements are optional, they can improve readability by indicating clearly what should happen when a number is not a multiple of 3 or 5. The code would continue to function without the else statements, although it could be less evident what is happening.


Conclusion

In this blog we talked about a common way to quickly assess a candidate's coding abilities using a programming problem called FizzBuzz. And showed you a way to solve the programming problem.

Top comments (0)