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.
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
The same applies to the other two acceptance criteria.
If we try and perform this task in Python, we could write something as follows:
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.