FizzBuzz in C#

Published on

Ever tried to solve FizzBuzz with C#? Here’s a simple solution to the age old interview question.

I’ve done a few coding interviews over the last couple of weeks, not uncommon for a developer seeking greener pastures.

A prevalent question in my recent examinations has been the FizzBuzz question.

Disclaimer: don’t think interviewers should ask candidates to solve FizzBuzz in an interview.

Nearly every candidate is going to learn how to solve FizzBuzz when studying common coding interview questions.

So how do you tell the difference between someone who can think their way through a problem, and someone who studied the problem beforehand?

Most experienced developers roll their eyes at the mere mention FizzBuzz simply because it’s one of those problems that nearly every developer will study before interviewing. Making the FizzBuzz problem somewhat redundant.

Well today I wanted to write my thoughts on how I approached the problem using C# in a recent interview. And in some later blogs i’d like to talk about some of the better technical interview questions i’ve encountered.

The Standard FizzBuzz

You’ll normally be given the following problem to solve:

Literate through numbers 1 to 100. For each number that is evenly divisible by 3, output the word “Fizz”. For every number that is evenly divisible by 5, output the word “Buzz”. Output the word “FizzBuzz” if the word is divisible by both 3 and 5.

Sounds easy right?

What Are Interviewers Hoping To Achieve Here?

The interviewer is hoping that the candidate can demonstrate the following:

  1. The candidate can implment a loop.
  2. The candidate can output text.
  3. The candidate is aware of the remainder operator and can use it to divide. I C# we use the % percentage symbol.

The usual solution

using System;
using System.Collections.Generic;
namespace FizzBuzzSolution
{
    class Program
    {
        // generates a list of integers from 1 to 100
        public static List<int> GetIntegers()
        {
            var integerList = new List<int>();
            for (var i = 1; i <= 100; i++)
            {
                integerList.Add(i);
            }
            return integerList;
        }
        // literates through a list of integers and write the appropriate string to the console
        public static void FizzBuzz(List<int> integerList)
        {
            foreach (var item in integerList)
            {
                if (item % 3 == 0 && item % 5 == 0)
                {
                    Console.WriteLine("FizzBuzz");
                }
                else if (item % 3 == 0)
                {
                    Console.WriteLine("Fizz");
                }
                else if (item % 5 == 0)
                {
                    Console.WriteLine("Buzz");
                }
            }
        }
        static void Main(string[] args)
        {
            var integerList = GetIntegers();
            FizzBuzz(integerList);
            Console.ReadLine();
        }
    }
}

Common Mistakes

Let’s try to understand the common gotcha’s with the FizzBuzz problem.

Ordering Of If Statements

Be sure to check for FizzBuzz (the number is divisible by 3 AND 5) before checking for either Fizz, or Buzz. Fort example, the below code would trigger on Fizz instead of FizzBuzz on the number 15.

foreach (var item in integerList)
  {
    if (item % 3 == 0)
    {
      Console.WriteLine("Fizz");
    }
      else if (item % 5 == 0)
    {
      Console.WriteLine("Buzz");
    }
    else if (item % 3 == 0 && item % 5 == 0)
    {
      Console.WriteLine("FizzBuzz");
    }
}

Forgetting To Use The Remainder Operator

We only want to print something if our number if divisible by 3 or 5 without decimals after the result.

For example, 5 divided by 3 is 1.666. There are numbers after the decimal point so it isn’t divided evenly. That’s why we check that the remainder is zero after every devision.

Using For Loops Instead of Foreach

Foreach loops are a cleaner and more modern way to loop through a list.

While there’s technically nothing wrong with using a standard for loop. You’re missing the opportunity to demonstrate your ability to write clean and contemporary code.

Alternative Solution using LINQ

C# developers are increasingly expected to understand LINQ, especially in anything more than a junior role. So here’s a nice FizzBuzz solution using LINQ.

public static void FizzBuzzLinq()
{
    Enumerable.Range(1, 100).ToList()
    .ForEach(x =>
    {
        Console.WriteLine("{0}{1}{2}",
    x % 3 == 0 ? "Fizz" : "",
    x % 5 == 0 ? "Buzz" : "",
    x % 3 != 0 && x % 5 != 0 ? x.ToString() : "");
    });
}

Article Categories: # c# # fizzbuzz # .net
Date Published: Aug 27, 2019

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.