More on Fizzbuzz
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:
// 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
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.
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.