FizzBuzz–A Programming Question

Computer Science Teacher
Computer Science Teacher - Thoughts and Information from Alfred Thompson

FizzBuzz–A Programming Question

  • Comments 48

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?” Smile)  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



  • A simple list of pre-prepared answers is by far the easiest to write, to verify, to read &c.

    If this were for a safety-critical application, this would be the only approach that I would accept.

  • Would not the fastest solution that meets the brief (and only take a single line) be:

    Print("1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 etc")

  • The print statement method is fast. It is only as reliable as the typist though and highly prone to cut/paste errors. And then there is the matter of scale. How easy is it to modify the routine to handle the numbers between 1 and 1,000,000,000? Or to use some arbitrary starting and ending points? Good coders think about expandability and maintainability.

  • Some of the languages (including C) allow you to write the most unreadable code only understood by the compiler and the writer.  If I saw something like this on the job (yes, production code),

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

    I would reject it in the code review.  Yes, it is quick, but it is not teaching the student to do a professional job.  Will this person be able to maintain it in six months?  Will someone else understand it?  How long will it take someone else to understand it.  In business, time is money.  If a programmer needs to take extra time to understand this type of code (assuming that the whole program is written like this), then your business is wasting valuable time and money.  Something like

    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>");

    As a teacher preparing students for their professional life as software engineers, it is most important to instill the idea that code readability is important.

  • Was playing a bit with C++ syntax and came up with this...

    #include <iostream>

    #include <iomanip>

    bool setFalse(bool& var)

    {

       var = false;

       return true;

    }

    int main()

    {

    bool printNum;

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

    {

       printNum = true;

       std::cout<<std::setw(3)<<std::setfill('0')<<i<<std::setw(0)<<" : ";

       std::cout<<(i%3==0?(setFalse(printNum)?"Fizz":""):"")<<(i%5==0?(setFalse(printNum)?"Buzz":""):"");

       printNum?std::cout<<i:std::cout;

       std::cout<<std::endl;

    }

    return 0;

    }

  • If any one have a problem about asp.net than told me i solve it send me your problem on katarmalvk@gmail.com

  • A simple solution without mod.

    int main()

    {

       int counter3=0;

       int counter5=0;

       int flag=0;

       int i=0;

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

       {

               flag=1;

               printf("%d ",i);

               if(++counter3==3) {counter3=0; printf("Fizz"); flag=0;}

               if(++counter5==5) {counter5=0; printf("Buzz"); flag=0;}

               if(flag) printf("%d",i);

               printf("\n");

       }

    }

  • My Python answer

    g = lambda(i):(i%3==0 and i%5==0 and 'FizzBuzz') or (i%3==0 and 'Fizz') or (i%5==0 and 'Buzz') or i

    for i in range(1,101):

     print g(i)

  • Although it's not the most efficient way (it could be done with modulo), here is my solution. I've allowed expansion to an arbitrary number of search terms, as most solutions already presented are hard-coded to 3 and 5, and would make it difficult or impractical to add, for instance, "Woo" on every instance of 2 (making 30, 60 and 90 "WooFizzBuzz").

               int number, i;

               int[] count;

               string output;

               int [] multipler = {3, 5}; // add numbers here

               string[] words = {"Fizz", "Buzz"}; // corresponding words

               count = new int[multipler.Length]; // use a count rather than modulo

               for (i = 0; i < count.Length; i++)

                   count[i] = 1;

               for(number = 1; number <= 100; number++)

               {

                   output = "";

                   for (i = 0; i < multipler.Length; i++)

                   {

                       if (count[i] == multipler[i])

                       {

                           output += words[i];

                           count[i] = 0;

                       }

                       count[i]++;

                   }

                   if (output == "")

                       output = number.ToString();

                   Console.WriteLine(output);

               }

               Console.ReadLine();

  • Enumerable.Range( 1, 100 ).Select(

     i =>

       i % 15 == 0 ? "FizzBuzz\r\n" : i % 3 == 0 ? "Fizz\r\n" : i% 5 == 0 ? "Buzz\r\n" : String.Empty

    ).ToList().ForEach(

     Console.Write

    );

    Console.ReadLine();

  • This is what happens when you don't read the instructions properly :) Now prints the number if it's not FizzBuzz/Fizz/Buzz:

    Enumerable.Range( 1, 100 ).Select(

     i =>

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

    ).ToList().ForEach(

     Console.WriteLine

    );

    Console.ReadLine();

  • ...and the fixed aggregate version:

    Console.Write(

     Enumerable.Range( 1, 100 ).Aggregate(

       String.Empty, ( current, i ) =>

         current + ( i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i.ToString() ) + "\r\n"

     )

    );

    Console.ReadLine();

  • Extensible version (similar to Adam's but more LINQy):

    var words = new Dictionary<int, string> {{3, "Fizz"}, {5, "Buzz"}};

    Enumerable.Range( 1, 100 ).Select(

     i =>

       words.Any( wordPair => i % wordPair.Key == 0 ) ?

         words.Where( wordPair => i % wordPair.Key == 0 ).Aggregate(

           String.Empty, ( current, wordPair ) =>

             current + wordPair.Value

         )

       :

         i.ToString()

    ).ToList().ForEach( Console.WriteLine );

    Console.ReadLine();

  • Would the students get any credit for pointing out that there is an infinite number of "the numbers from 1 to 100"?

  • A good question. The proper answer is probably to specify Integers between 1 and 100. :-)

Page 3 of 4 (48 items) 1234