Your else
belongs only to the last if
:
if (val1 % 15 == 0)
cout << "FizzBuzz\n";
if (val1 % 3 == 0)
cout << "Fizz\n";
if (val1 % 5 == 0)
cout << "Buzz\n";
else // any val1 which doesn't divide by 5
cout << val1 << "\n";
That's why, if val1
is not divisible by 5, it outputs this value.
Also, 15 is divisible either by 15, 5 and 3. It triggers all three if
s and outputs all three lines.
You can use else if
in order to get the correct results but the best way is to replace it with terminating execution on completed condition.
For example, if you had a function you would be able to do it this way:
string GetOutput(int val)
{
if (val % 15 == 0) return "FizzBuzz";
if (val % 3 == 0) return "Fizz"; // 2. val % 15 != 0 implied
if (val % 5 == 0) return "Buzz"; // 3. val % 15 != 0 && val % 3 != 0 implied
return to_string(val1); // 4. val % 15 != 0 && val % 5 != 0 && val % 3 != 0 implied
}
int main() {
cout << GetOutput(val) << endl;
}
It would work because execution terminates on true
condition, and any condition check implies that all previous are false. These two rules are guaranteed to be correct in this example:
1. If execution is at lines 2 or 3 - val is not divisible by 15
2. If execution is at line 4 - val is not divisible by 3, 5 and 15
With this approach, you don't need to describe these conditions manually.
Moreover, if you have more and more conditions, it will be much easier to maintain and read such function than write very long logic condition.
For example,
string GetOutput(int val)
{
if (val % 64 == 0) return "FizzBuzz"; // such wow
if (val % 32 == 0) return "Fizz"; // much readable
if (val % 16 == 0) return "Buzz";
if (val % 8 == 0) return "Muzz";
if (val % 4 == 0) return "Guzz";
if (val % 2 == 0) return "Duzz";
return "Hizz";
}
instead of
if (val % 64 == 0) cout << "FizzBuzz";
if (val % 64 != 0 && val % 32 == 0) cout << "Fizz";
if (val % 64 != 0 && val % 32 != 0 && val % 16 == 0) cout << "Buzz";
if (val % 64 != 0 && val % 32 != 0 && val % 16 != 0 && val % 8 == 0) cout << "Muzz";
if (val % 64 != 0 && val % 32 != 0 && val % 16 != 0 && val % 8 != 0 && val % 4 == 0) cout << "Guzz";
if (val % 64 != 0 && val % 32 != 0 && val % 16 != 0 && val % 8 != 0 && val % 4 != 0 && val % 2 == 0) cout << "Duzz";
if (val % 64 != 0 && val % 32 != 0 && val % 16 != 0 && val % 8 != 0 && val % 4 != 0 && val % 2 != 0) cout << "Hizz";
or
if (val % 64 == 0)
{
cout << "FizzBuzz";
} else {
if (val % 32 == 0)
{
cout << "Fizz";
} else {
if (val % 16 == 0)
{
cout << "Buzz";
} else {
if (val % 8 == 0)
{
cout << "Muzz";
} else {
if (val % 4 == 0)
{
cout << "Guzz";
} else {
if (val % 2 == 0)
{
cout << "Duzz";
} else {
cout << "Hizz";
}
}
}
}
}
}