-8

I'm trying to see if I can make a fizzbuzz c++ switch statement. I'm getting an error saying i is not usable in a const expression. Does that mean I can't make this thing work? Or is there a work around? Here's my code.

#include <iostream>
using namespace std;

int main() {
    for(int = 1; 1 <= 100; i++){
        switch(true){

            case(i % 3 == 0 & i % 5 == 0):
                cout << "fizzbuzz" << endl;
                break;

            case(i % 3 == 0):
                cout << "fizz" << endl;
                break;

            case(i % 5 == 0):
                cout << "fizz" << endl;
                break;
            default:
                cout << i << endl;
        }
    }
}

3 Answers3

6

If you really want to use switch/case then you could do it like this:

switch (i % 15)
{
    case 0 : cout << "fizzbuzz\n"; break;

    case 5:
    case 10: cout << "buzz\n"; break;

    case 3:
    case 6:
    case 9:
    case 12: cout << "fizz\n"; break;

    default: cout << i << "\n"; break;;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
1

There are a couple of fundamental problems with how you're using switch/case.

The expected way to use it is to have the switch refer to a variable or expression, then the case sections refer to constant values.

Instead what you're doing is switch(true) which doesn't make any sense, even though it compiles. It's equivalent to switch(1). So in that case only case 1: would ever apply.

You cannot use expressions for case. These must be constant integer values. So for example you can either plain integers case 0:, or also commonly pre-processor defines case FIZZBUZZ:.

MrJLP
  • 978
  • 6
  • 14
0

As stated in the comments, several times, you cannot always use a switch() statement like a if statement and there are several other issues with your code. I am not going to give you the right answer as I don't believe that will help you the most.

Here are some notes:
1) Instead of a switch you should use if, else if, and else statements.
2) In C++ a and is expressed as && not &
3) A for loop is declared like for(int i = 0; i <= 100; i++)

You should watch/read some simple tutorials on how to code C++ as it is important you understand these basics.