-2

Tried writing fizzbuzz out in C++, but prior to the console printing the list of integers it prints each string "Fizzbuzz, "fizz", "buzz"

Sample output:

   Fizzbuzz
   Fizz
   Buzz
   1
   2
   Fizz
   4

Code:

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {

    int i;
    for (i = 0; i <=100; i++) {
        if((i % 15) == 0)
                cout << "Fizzbuzz" << endl;
        if((i % 3) == 0)
                cout << "Fizz"<< endl;
        if((i % 5) == 0)
                    cout << "Buzz" << endl;
        else
            cout << i <<endl;
    }


}
default locale
  • 13,035
  • 13
  • 56
  • 62
ayeteo
  • 244
  • 3
  • 5
  • 14

1 Answers1

2

When checking for multiple conditions, for which only one branch should be taken, you need to use else ifs after the first if. Then, the first branch for which the condition is met, will be taken:

    if((i % 15) == 0)
        cout << "Fizzbuzz" << endl;
    else if((i % 3) == 0)
        cout << "Fizz"<< endl;
    else if((i % 5) == 0)
        cout << "Buzz" << endl;
    else
        cout << i <<endl;

In your code, each condition gets checked, and each branch will be taken for which the condition is met. The else case in your code will be taken if the last if was not taken, i.e. it belongs to the last if only. When using else if, the else branch is taken if none of the conditions was met.

leemes
  • 44,967
  • 21
  • 135
  • 183