A C# Code Solution for FizzBuzz

Posted by Steven Suwatanapongched on September 15, 2008

I read a slashdot article earlier today which lead me to a Coding Horror article: Why Can’t Programmers.. Program?. This lead me to the FizBuzz problem, which prompted me to write my own quickie solution in C# (as a console application).

Problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

My Quick Solution:

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

{

    if ((i % 3 == 0) && (i % 5 == 0))

    {

        Console.WriteLine("FizzBuzz");

    }

    else if (i % 3 == 0)

    {

        Console.WriteLine("Fizz");

    }

    else if (i % 5 == 0)

    {

        Console.WriteLine("Buzz");

    }

    else

    {

        Console.WriteLine(i.ToString());

    }

    }

    Console.ReadLine();

I know my version is probably not optimal, nor is it the shortest way to write it. I just wanted to write it for fun, code for fun. I honestly can’t remember the last time I coded something purely for fun. Now I’m wondering how I can optimize this in C# and even how to write it in other languages.

Where I formatted my C# code into HTML for Blogspot: http://formatmysourcecode.blogspot.com