# FizzBuzz question

"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”." from http://c2.com/cgi/wiki?FizzBuzzTest

the below prints the multiples of 3 and of 5 but not of both. Why?
``````#include <iostream>

using namespace std;
int main(int argc, const char * argv[])
{
for (int i = 1; i < 101; i++)
{

if(i % 3 == 0)
{
cout << "Fizz" << endl;
}
else if(i % 5 == 0)
{
cout << "Buzz!" << endl;
}
else if ((i % 3 == 0) && (i % 5 == 0))
{
cout << "FizzBuzz, WHAAAAT!" << endl;
}
else
{
cout << i << endl;
}
}

return 0;
}
``````
###### Who is Participating?

Commented:
At present suppose i = 15

Then
i %3 ==0 is true
i % 5 == 0 is also true

But the first condition wins.

If you reverse the order of your conditions, put the third condition first, it should work too!
0

Commented:
It's

``````else if ((i % 3 == 0) && (i % 5 == 0))
``````
``````else if ((i % 3 == 0) || (i % 5 == 0))
``````
0

Commented:
You statement:
else if ((i % 3 == 0) && (i % 5 == 0))

Is correct.  However this condition will never reach and if a number is divisible by both 3 and 5, 3 being in the first condition will win.

There are many ways to fix it but one way is to change the conditions like

First condition
if ((i % 3 == 0) && (i % 5 != 0))

And second like
if ((i % 3 != 0) && (i % 5 == 0))
0

Author Commented:
Yes, moving the double condition to the top of the if-else tree did the trick. Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.