Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

A classic question used by interviewers to determine if a candidate is worthy of their precious time. You would have thought that such a simple question would be reserved for the more junior applicant but I have seen it used irrespective of experience.

As with all programming questions the major pitfalls here are not seeing the bigger picture and coding your way into a corner when it comes to the kicker “multiples of both three and five”. With all of your focus on the pass cases, you must also remember to print out the number in the fail case where *i* is not divisible by 3 or 5.

The meat of the problem is pretty easy to see, to determine if x (the dividend) is divisible by y (the divisor) we use the mod operator. However this solution will only work on the basis that we are dealing with a non zero divisor. The divisor is outlined in the question as 3 and 5 so this approach will work, but we have outlined a potential issue should we be prompted to parameterise. It is also worth noting 2 important characteristics of mod that;

– if the dividend happens to be zero the mod will be zero

– in c++ the sign of the mod matches the sign of the dividend

So as we may remember the mod operator divides the dividend by the divisor and returns the remainder.

9 mod 3 = 0 (quotient:3, remainder:0) // pass case

5 mod 3 = 2 (quotient:1, remainder:2) // fail case

What the interviewer is also looking for here is how you layout the 4 possible outcomes..

– Print the number if not a multiple of 3 or 5

– Print Fizz if a multiple of 3

– Print Buzz if a multiple of 5

– Print FizzBuzz if a multiple of 3 and 5

There a multitude of ways to do this, but I feel this approach to be readable and concise;

void FizzBuzz(int begin, int end) { for (int i = begin; i <= end; i++) { bool div3 = i != 0 && i % 3 == 0; bool div5 = i != 0 && i % 5 == 0; if (div3 && div5) { printf("\nFizz Buzz"); } else if (div3) { printf("\nFizz"); } else if (div5) { printf("\nBuzz"); } else { printf("\n%d", i); } } }

## Leave a Reply