Fizz Buzz is a word game to help teach division. Players take turns to count incrementally, replacing any number divisible by three with the word “fizz” and any number divisible by five with the word “buzz” and any number divisible by both three and five is replaced with the word “fizzbuzz”.
For example, a typical round of fizz buzz would start as follows:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizz Buzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, Fizz Buzz, 31, 32, Fizz, 34, Buzz, Fizz
The Fizz Buzz game might seem to be a very simple problem to solved with code but many interviewers still use this test to see if the job candidate can solve simple problems. Writing a program to output the first one hundred Fizz Buzz (often spelled FizzBuzz when talking about the game in programming) numbers should be a trivial problem for any computer programmer, so interviewers can easily dismiss those with insufficient programming ability.
Just like any other computer problem, there are a tons are possible solutions and I’ve included mine below but before you take a look at my solution, why not try to solve the Fizz Buzz problem for yourself?
The Fizz Buzz problem broken down is as follows:
Here is my cSharp solution of the Fizz Buzz test. The source code can be found on my GitHub page.
To solve the problem you will have to implement the relatively rarely used %
operator, called the modulus. The modulus returns the remainder of a division.
For example:
9 % 4 = 1
and 40 % 10 = 0
In the first example, the answer to the equation is one and the reason for this is because you can fit four twice into nine and have a remainder of one. In the second example the answer to the equation is zero and the reason for this is because we can fit ten into fourty four times with no remaining value.
Now that you understand modulus, we can now code a solution to the Fizz Buzz problem.
i
by one for each loop.output
.i
is divisible by three.
output
parameter.i
is divisible by five.
output
parameter. output
parameter is empty.
i
is not divisible by three or five, so I append the value of i
to the output
parameter instead.output
parameter to the console. So to recap:
output
parameter is"Fizz", i
was divisible by three. output
parameter is "Buzz" i
was divisible by five. output
parameter is "FizzBuzz", I know the value of i
was divisible by both three and five. i
was not divisible by three or five. using System;
namespace FizzBuzzSolution
{
class Program
{
private const string Fizz = "Fizz";
private const string Buzz = "Buzz";
static void Main(string[] args)
{
Console.WriteLine("FizzBuzz Solution");
Console.WriteLine("");
for (int i = 1; i <= 100; i++)
{
var output = "";
if (i % 3 == 0)
output += Fizz;
if (i % 5 == 0)
output += Buzz;
if (String.IsNullOrWhiteSpace(output))
output = i.ToString();
Console.WriteLine(output);
}
Console.ReadLine();
}
}
}