Codiqo

Learn C# · lesson 21 of 61 · about 9 minutes

Project: FizzBuzz

The crowd chants the hero's victory: check how far they want to count, then count with Fizz for 3s and Buzz for 5s.

What you'll learn

  • Test divisibility with %
  • Order conditions correctly
  • Read the limit from input

The victory chant

When the battle is over, the crowd chants. Someone picks how far to count, from 1 to 30, and the crowd calls out every number: Fizz for a multiple of 3, Buzz for a multiple of 5, FizzBuzz for both. It's the classic interview puzzle, FizzBuzz.

The rules

Count from 1 to n. For multiples of 3 say Fizz, for multiples of 5 say Buzz, for multiples of both say FizzBuzz, otherwise say the number.

The trick: check "both" (divisible by 15) first.

FizzBuzz

int n = int.Parse(Console.ReadLine() ?? "15");
for (int i = 1; i <= n; i++)
{
    string say = (i % 15) switch
    {
        0 => "FizzBuzz",
        3 or 6 or 9 or 12 => "Fizz",
        5 or 10 => "Buzz",
        _ => i.ToString(),
    };
    Console.Write(say + (i < n ? " " : "\n"));
}

Output

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

The crowd checks the number first

int count = 5;
if (count < 1 || count > 30)
{
    Console.WriteLine("The crowd only counts from 1 to 30.");
}
else
{
    for (int n = 1; n <= count; n++)
    {
        if (n % 15 == 0) Console.WriteLine("FizzBuzz");
        else if (n % 3 == 0) Console.WriteLine("Fizz");
        else if (n % 5 == 0) Console.WriteLine("Buzz");
        else Console.WriteLine(n);
    }
    Console.WriteLine("Victory!");
}

Output

1
2
Fizz
4
Buzz
Victory!

Tip

The example uses i % 15 in a switch expression. The if / else if version in the exercises works the same way; choose whichever reads more clearly to you.

Now try it yourself

This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.