Solving FizzBuzz problem in C#

FizzBuzz problem is a simple algorithm test given in interviews. I think I received this at least five times. So you will probably also receive it at your following interview.

The problem sounds like this:

Write a program that prints the number from 1 to N:

  • If an integer is divisible by 3, then print Fizz.
  • In case it is divisible by five, then print Buzz.
  • If the number is divisible by both 3 and 5, then print FizzBuzz.
  • In other cases, print the number.

Here is an example of a sequence:

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

Solution for FizzBuzz interview question

To solve this problem, you will need a for loop and an if-else statement:

for (int i = 1; i <= N; i++)
{
   if (i % 15 == 0)
    {
        _textWriter.Write("FizzBuzz");
    }
    else if (i % 3 == 0)
    {
        _textWriter.Write("Fizz");
    }
    else if (i % 5 == 0)
    {
        _textWriter.Write("Buzz");
    }
    else
    {
        _textWriter.Write(i);
    }
    _textWriter.Write("\n");
}

First, you check if the number is divisible by 15 because numbers that are divisible by both 3 and 5 need to be printed differently. Then you check if it’s divisible by 3 or 5.

Here you can find the repository that contains the solution.

Another solution is to use only if statements.

for (int i = 1; i <= 100; i++)  
{  
        string currentString = "";  
        if (i % 3 == 0)  
        {  
            currentString += "Fizz";  
        }  
        if (i % 5 == 0)  
        {  
            currentString += "Buzz";  
        }  
        _textWriter.WriteLine(currentString.Length==0?i.ToString():currentString);  
}

There are multiple ways to solve this problem. Feel free to find new ways. This problem is pretty simple, but interviews love to use it because it filters very fast the suitable candidates.

Leave a Comment