Fizz buzz question and solution in C++ – C++ Practice Assignment 9

The Fizz buzz question is popular among programmers going for job interviews as it’s designed to weed out people that cannot program. From this article on “Why Can’t Programmers..Program, an alarming majority of comp sci graduates and senior programmers take more than 10-15 minutes to write a solution.

The assignment of the Fizz buzz question is to 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”. The key to solving this problem is using the Modulo operation. To solve this problem you simply need to iterate from 1 to 100 using a for loop and check if each number is divisible by 3, 5 or both.

Here is the C++ solution


//-------------------------------------------------------------------------------
// FizzBuzz C++ Solution
// 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".
//-------------------------------------------------------------------------------

#include <iostream>

using namespace std;

int main()
{
// Print numbers from 1 to 100
for (int i = 1; i < 101; i++)
{
// Check to see if's both divisable by 3 and 5
if (i % 3 == 0 && i % 5 == 0)
{
cout << "FizzBuzz" << endl;
}
// Check to see if it's divisable by 3
else if (i % 3 == 0)
{
cout << "Fizz" << endl;
}
// Check to see if it's divisable by 5
else if (i % 5 == 0)
{
cout << "Buzz" << endl;
}
else
// Print out the rest of the numbers from 1 to 100
cout << i << endl;
}
}