The FizzBuzz Problem

Posted: July 20, 2011    Author:     Category:  Programming

The FizzBuzz problem is a fairly straight forward coding problem that requires you to write a program that prints out all the numbers between 1 and 100. It should print “Fizz” for each number that’s a multiple of three, “Buzz” for each number that’s a multiple of five and “FizzBuzz” for each number that’s a multiple of both five and three.

I approached this by first creating a loop that looped through all the numbers between 1 and 100, then I put several checks inside the for loop in the form of “if-else” statements. A number, i, that’s a multiple of 3 will cause the statement “i%3” to evaluate to 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
int main() {
 
        for ( int i = 1; i <= 100; i++ ) {
 
                if( i % 3 == 0 && i % 5 == 0 )
                        std::cout << i << " FizzBuzz" << std::endl;
 
                else if( i % 3 == 0 )
                        std::cout << i << " Fizz" << std::endl;
 
                else if( i % 5 == 0 )
                        std::cout << i << " Buzz" << std::endl;
 
                else
                        std::cout << i << std::endl;
 
        }
 
        return 0;
 
}

This is a simple solution, I’m sure there’s a more efficient answer but this is what I came up with within the first few minutes of reading the problem.

 

Leave a Reply

Home Programming The FizzBuzz Problem