Skip to content

More on Fizzbuzz

March 2, 2010

For those who have come here searching for the shortest Java Fizzbuzz, I don’t have it.  However, Chris Drost has close to the best you can do and still remain legible.

As far as mine goes, I like it because it is easily read and the concepts behind it are cohesive.  This is a quick walk through of the meat of the code:

boolean flag;
// I’m starting out with a flag to keep track of when I use the word “fizz” or “buzz”.
// that way I can choose to write my counter when I don’t use either.

for (int i = 1; i<=100;i++)// i is my counter –

flag = false;// set the flag to false for each time around
if (i%3==0)

System.out.print(“Fizz”);// prints “Fizz” when the counter is divisible by three

//note I haven’t gone to a new line – if “Buzz” gets printed, it will go next to “Fizz”
flag = true; // tells me that I used a word.

if (i%5==0)

System.out.print(“Buzz”);// prints “Buzz” when the counter is divisible by five
flag = true;// again tells me that I used a word.

if (flag == false)// i.e. if I haven’t used “Fizz” or “Buzz”.

System.out.print(i);// prints the number counter is on

System.out.println();// NOW we go to a new line


And that’s it!

I debated using the flag for the integer print – I could have done it by testing that i mod 3 and i mod 5 are both non zero (or even testing that (i mod 3) * (i mod 5) is non zero), but I figure checking a flag is cleaner than redoing the same math a second time).

I also debated having a separate test for the “fizzbuzz” condition – it might even make it more readable – but decided that the implicit concatenation was more in line with the spirit of the game 🙂

Now that I have wasted enough time on what any competent programmer would spend at most 5 minutes on, I’ll drop the subject.


From → Code

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: