What is Fizz Buzz?

Fizz buzz is a common programming interview question.

The problem statement usually reads something like this:

Write a short program that prints each number from 1 to 100 on a new line.

For each multiple of 3, print “Fizz” instead of the number.

For each multiple of 5, print “Buzz” instead of the number.

For numbers which are multiples of both 3 and 5, print “FizzBuzz” instead of the number.

Hackerrank.com

If we break this down, the challenge is for us to prove that we know how to:

  • Loop through a specific set of numbers
  • Tell if something is a multiple of 3
  • Tell if something is a multiple of 5
  • Tell if something is a multiple of both 3 and 5
  • Know the correct order to check the above cases
  • Ignore everything else

The main thing here is to know about the modulo operator (%). As that tells us if there are remainders after the division of one number by another.

So if we applied a modulus query such as i % 3 == 0, then we would know if that specific number had any remainders, meaning that it is perfectly divisible by 3. This is where we’d print "Fizz".

The same applies to the other two acceptance criteria.

If we try and perform this task in Python, we could write something as follows:

for i in range(1,101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Note how we first do the 3 and 5 check, before doing the individual cases, this is to make sure we don’t print out the individual cases should both numbers match.

The answer is almost identical if we chose to do it in Javascript, as opposed to Python:

for (var i=1; i<101; 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);
    }
}
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments