FizzBuzz Solution in C#

FizzBuzz Solution in C#

A common programming problem

One of the most popular coding challenges is FizzBuzz. It may not be the most challenging of the challenges, but it stumps enough developers to be used frequently. The problem is this: print all the numbers from 1 to 100 to the console. However, every number that is divisible by 3: print Fizz, every number that is divisible by 5: print Buzz, and every number divisible by 3 AND 5: print FizzBuzz.

Here's how I would solve this challenge in C Sharp

Since I know that I want to stop running the program at 100, I'm going to use a for loop. For loops are more favorable when you know the exact number of times you want to iterate.

for (int i = 1; i <= 100; i++)
{

}

I'm starting the iteration at 1 instead of 0 for a couple of reasons: Neither 3 nor 5 are divisible by 0 and it doesn't make a lot of logical sense to print 0 to the console. Most people, at least people who aren't programmers, start counting at 1. Then I iterate until I hit 100, incrementing by "i" by 1 every loop.

Create a string to append values to

using System.Text;

for (int i = 1; i <= 100; i++)
{
    StringBuilder sb = new StringBuilder();
}

Why use a StringBuilder instead of just a string? Strings in C# are immutable, which means you can't change their values. So if you want to create an empty string and append a string value to that empty string, c# doesn't simply add that value to your empty string. Behind the scenes, it creates a new string of the concatenated empty string and the new string value. This can be inefficient in larger programs.

A StringBuilder is a mutable sequence of characters. This means that you can edit its contents as many times as you wish without needlessly creating new strings behind the scenes. You'll see this in action in the next steps.

Appending Fizz, Buzz, or FizzBuzz

If you recall from the intro to my blog post, I stated that we need to print Fizz if the index is divisible by 3, Buzz if the number is divisible by 5, or FizzBuzz if the number is divisible by both 3 AND 5.

using System.Text;

for (int i = 1; i <= 100; i++)
{
    StringBuilder sb = new StringBuilder();
    if (i % 3 == 0) 
    {
        sb.Append("Fizz");
    }
    if (i % 5 == 0)
    {
        sb.Append("Buzz");
    }
}

There are a few things to note about the code above: I'm using the modulus operator to verify if the index is divisible by 3 or 5. If 3 or 5 goes into "i" evenly, then append "Fizz" or "Buzz" respectively. Also note how I don't use an else-if statement, but two individual if statements. This is done purposely for efficiency. This way if "i" is divisible by 3 AND 5, then it appends both "Fizz" and "Buzz" to "sb", making that iteration "FizzBuzz". I think that's pretty slick!

Printing the values to the console

Now it's time to wrap up the StringBuilder as a string or print the index to the console. Since StringBuilder is a mutable sequence of characters, we need to turn it into a string to print it to the console.

using System.Text;

for (int i = 1; i <= 100; i++)
{
    StringBuilder sb = new StringBuilder();
    if (i % 3 == 0) 
    {
        sb.Append("Fizz");
    }
    if (i % 5 == 0)
    {
        sb.Append("Buzz");
    }

    if (sb.Length > 0)
    {
        string str = sb.ToString();
        Console.WriteLine(str);
    }
    else
    {
        Console.WriteLine(i.ToString());
    }
}

Here, I check the length of "sb" and verify that it isn't empty. If it's not empty, then I use the ToString() method to convert "sb" into a string and print that string to the console. If "sb" is empty, then we print the index to the console after converting it to a string.'

Note: It's important to convert your StringBuilder object to a string at the very end of your function. If you convert it too soon, you'll have the same issues of working with immutable strings.

Wrapping Up

If you run this code in your preferred IDE, you'll see the values of 1 through 100 printed to the console except for numbers divisible by 3, 5, and 3 AND 5. This isn't one of the hardest challenges out there, but it can hang up a lot of developers.