# FizzBuzz–A Programming Question

Computer Science Teacher

### FizzBuzz–A Programming Question

Projects or exercises that lend themselves to many different “correct” solutions are just about the best sorts of learning experiences I can imagine. They really open the possibilities for discussion and from discussion – questions, answers, explanations – comes real learning. Recently Dennis Shaw, a student at Old Dominion University and a Microsoft Student Partner, told me about the FizzBizz exercise. (see Using FizzBuzz to Find Developers who Grok Coding for where it comes from) This is exactly that sort of multiple solution but not that difficult sort of exercise I love. Briefly stated the exercise is:

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”.

So there you have it. It involves using some sort of conditional of course. Nested or unnested? It can be done either way. Which way is best? Do you check for multiples of three first or five? Do you check to see if the number ISN’T one of those cases  first or if it IS one of those cases? Or rather than If statements is there a different way completely? Perhaps a select/case structure? Does creating functions/methods complicate of simplify the result? If students know multiple programming languages is there one that is better for this than another (think especially about functional languages v. procedural languages). Are there special operators (like perhaps the ternary operator in C#, C/C++ and Java) that might make the code “tighter?” Is there a trade off between complication and understanding? Oh and of course, does your solution actually work?

Justify your answers. (Don’t you just just love the teacher-ness of “justify your answer?” )  I can see asking students to write up an explanation of how their solution works and why they did it that way as a means for forcing examination of the solution. And as a side benefit a lot of students can benefit from yet another writing exercise. Code that can’t be explained isn’t properly understood and that causes problems in the long run. A piece of code should not be “magic” to the person who wrote it.

There are many solutions on the Internet to the FizzBuzz question. So yes, some student might go searching for one and even try to use it. The “justify your solution” question means that they still have to understand and explain how it works and why they like it. I can’t see a student saying “I like this solution because I found it on the Internet and it works.” Well, I hope they wouldn’t try that. But if they do, grade them on how well they explain the benefits of using borrowed code and if they credited the original source properly. And of course they should also be able to explain why this solution is better than others they might have found. Surely they were not so lazy as to hand in the first solution they found?

BTW a couple of related posts of mine are Teaching, Learning and the Job Interview and Characteristics of a Good Programming Project

• Here are a few more fizzbuzz-type questions: stackoverflow.com/.../alternate-fizzbuzz-questions

• I've taken this challenge in the past.

Here's the link to my C++ version:

I've also done a C# one but it's not on codepad. (Curse them for not supporting .Net!)

So which approach did I take? I actually approached it from the maximum readability standpoint.

As such, I use (cringes are expected from hardcore programmers) booleans! And though I don't check for 15 specifically, the way I created the code makes 15s work out perfectly too.

In short, the Psuedo-language for this would be "Print fizz if multiple of 3, buzz if multiple of 5, the number if neither applies." - Noting that if 3 and 5 are both true, fizz and buzz both get printed!

I tend to avoid ternaries. They make the character count smaller true, but the readability usually suffers. They offer absolutely no compiler benefit.

I think that covers all the questions presented herein. And I will concede that there are many "right answers" - but which is "best" is subjective.

Mine is best, of course. Haha.

• One more note. You might want to check out projecteuler.net if these kids of problems tickle your fancy. =)

• Actually a site that is good for this sort of thing is http://pex4fun.com Supports C#, Visual Basic and F#.

• @Keith - if mod 15 - FizzBuzz elseif mod 5 Buzz elseif mod 3 Fizz else N - if two numbers are mutually prime the only numbers that have both of them as factors has their product as a factor.

• @anon - mod is definitely the way to go... as a math guy that's the first thing I thought of.

• I did a mathematical/binary/modular approach. Unfortunately the switch is unavoidable. https://gist.github.com/843803

Full explanation there.

• Posted too soon.  Here is the better version.  Done with java but via JSP as I primarily work in web development.  Fewest lines of code I could figure to solve the problem.  I added a new line character for readability.

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

String output = "";

if(i % 3 == 0) output = "Fizz";

if(i % 5 == 0) output += "Buzz";

if(output.equals("")) out.print(i+"<br>");

else out.print(output+"<br>");

}

•        Dim i As Integer = 1

Dim oWrite As System.IO.StreamWriter

oWrite = IO.File.CreateText("C:\Temp\fizzbuzz.txt")

While i <= 100

If (i Mod 3 = 0 And i Mod 5 = 0) Then

oWrite.WriteLine(CStr(i) + " - FizzBuzz")

ElseIf (i Mod 3 = 0) Then

oWrite.WriteLine(CStr(i) + " - Fizz")

ElseIf (i Mod 5 = 0) Then

oWrite.WriteLine(CStr(i) + " - Buzz")

Else

oWrite.WriteLine(CStr(i))

End If

i = i + 1

End While

oWrite.Close()

• This is based on a drinking game called Bizz-Buzz where you drank if you didn't get the correct numbers as each in the group counted from 1 to 100.  I lost a lot.  But, congrats on the ones who posted the code already!

• If you work where I do, you set up a web service that will return the string to print given the integer input. duh.

• FizzBuzz must be a hot topic for some reason, I saw it a few days ago on a web-design site. Over the years I have seen many plausible responses which actually helps me learn how to do things in other languages

The one that I had not seen (at least at the time) was doing it in SQL, so I developed this version. I did get reminded that SQL chooses the first match in a case statement and ignores the rest, so the 15 was the first check. I also do know that I could use string concatenation to build it, but it does not look as graceful.

DECLARE @Count INT

SET @Count = 1

DECLARE @FzBz VARCHAR(8)

WHILE @Count <= 100 BEGIN

SELECT @FzBz = CASE

WHEN (@Count % 15 = 0) THEN 'FizzBuzz'

WHEN (@Count % 3  = 0) THEN 'Fizz'

WHEN (@Count % 5  = 0) THEN 'Buzz'

ELSE CAST(@Count AS VARCHAR(8))

END

PRINT @FzBz

SET @Count = @Count + 1

END

• fizzbuzz.pastebin.com/ytRhRLAq

I love the ternaries in scripted languages, and I don't feel readability suffers because their syntax is so unique that one should know what they're looking at if they've ever encountered them before. I still think this could probably be condensed further -- just have this feeling at the back of my neck that I'm missing something -- but that almost certainly would impact readability.

I'll also note that while I used "\n" between integers in my sample, that was mostly because there's no practical application where this would need to be made pretty, and newline characters are two less code characters than a "<br>". :P

(My apologies if this is a repost. I just tried to submit, and there was no acknowledgement once the page loaded, nor was my comment listed.)

• C# Code

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

{

string s = "";

s = (i % 3 == 0) ? ((i%5==0)?"FizzBuzz":"Fizz") : ((i%5==0)?"Buzz":i.ToString()) ;

Console.WriteLine(s);

}

• C# Code- iam dumb, reduced one more line :)

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

{

string s = (i % 3 == 0) ? ((i%5==0)?"FizzBuzz":"Fizz") : ((i%5==0)?"Buzz":i.ToString()) ;

Console.WriteLine(s);

}