Is it possible to create the FizzBuzz solution in C# with the switch construct. I've found solutions that work for JavaScript and other languages, but these (or the syntax equivalent) don't seem to be working in C#.
For reference, I'll write the if statement version down below:
for (int x = 1; x <= 15; x++)
{
if (x % 5 == 0 && x % 3 == 0)
Console.WriteLine("FizzBuzz");
else if (x % 5 == 0)
Console.WriteLine("Buzz");
else if (x % 3 == 0)
Console.WriteLine("Fizz");
else
Console.WriteLine(x);
}
Console.ReadLine();
EDIT: forgot to put my switch statement code, sorry about that:
for (x = 1; x <= 15; x++)
{
switch (x)
{
case (x % 3 == 0 && x % 5 == 0):
Console.WriteLine("FizzBuzz");
break;
case (x % 5 == 0):
Console.WriteLine("Buzz");
break;
case (x % 3 == 0):
Console.WriteLine("Fizz");
break;
default:
Console.WriteLine(x);
break;
}
}
My problem is with the modulo statements. Error is "Cannot implicitly convert type bool to int. I've tried replacing switch (x)
with switch (true)
but that doesn't help much, just changes the error to "A constant value is expected" for each of my cases.