Fizz Buzz is a well known programming exercise, aimed to establish simply whether someone has a basic grasp of programming concepts or not. It’s the MOT test of programming exercises, and has sparked interesting debate in the past.
Here’s an example of a Fizz Buzz question:
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”.
Example output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
etc.
I was interested in uncovering any latent programming aptitude amongst NM’s non-programming collective, so I asked some team members if they’d like to have a go at solving Fizz Buzz.
Clive took the bait, and his interpretation is below, but before reading any further, perhaps you’d like to have a go at solving Fizz Buzz as well? It’s OK, I’ll hang on for you…
dum-de-dum…
OK. Welcome back. Here’s Clive’s version, which I find fascinating…
Clive forgot to stop at 100, but apart from that the implementation’s correct. What I find fascinating is that Clive’s construction of the loop, he derives each iteration manually, whereas a seasoned programmer would simply accept the loop as a given and start from there. This may be why so many non-coders find it so hard to start coding, not knowing what you get ‘for free’ and how much you can essentially take for granted. (As an aside, this also reminded me how easy it is to dismiss the monumental effort that has gone into the creation of the technology that surrounds us, and how we so often stand on the shoulders of giants. An idea that has been explored before brilliantly in the The Toaster Project).
I also love that Clive grokked the idea of working at a “meta” level, so instead of just writing instructions like:
print “1”
print “2”
print “Fizz”
etc.
He’s actually gone to the effort of uncovering and encoding the underlying logic, which is great!
Anyway, I find this stuff fascinating, but maybe it’s just me!
Feel free to post your Fizz Buzz solutions below… Here’s mine. :)




40 Comments
Great read. I love thinking about how people think about solving problems.
I posed a challenge to some coder friends to implement FizzBuzz *without* using IF statements. Here is my solution:
http://jsfiddle.net/jeremyx/WD9hF/
http://www.sparrowos.com/Wb/Demo/Asm/BuzzFizz.html#l1
Occurred to me that this is the first pseudocode I’ve written in many many years. Fun! I think this should work but don’t think it’s very elegant. I’m guessing this is quite a basic answer, which would be about right for me :)
For integer a = 1 to 100
flag = 0
If a MOD 3 = 0 then
print ‘fizz’
flag = 1
End if
If a MOD 5 = 0 then
print ‘buzz’
flag = 1
End if
If flag = 0 then
print a
End if
Print linebreak
Next a
Great observation about non-coders not knowing what they can get for free. An interesting exercise overall. Thank you!
(As an aside: in my version of Firefox the input field labels do not appear in the comment block. Is that intentional?)
#include
int main(void)
{
int i;
for (i = 1; i <= 100; i++)
{
if (!(i % 3) && !(i % 5))
printf("FizzBuzz\n");
else if (!(i % 3))
printf("Fizz\n");
else if (!(i % 5))
printf("Buzz\n");
else
printf("%d\n", i);
}
return 0;
}
@Jeremy Merritt
Here’s my FizzBuzz solution in javascript without if conditions.
http://bateru.com/news/2012/10/code-of-the-day-fizzbuzz-in-javascript/
The #include was for stdio.h
Not sure if this counts as not using an if statement.
https://gist.github.com/4178425
One line of python, with no conditionals:
print “\n”.join([str(("FizzBuzz","Fizz","Fizz","Fizz","Fizz",i,i,i,"Buzz",i,i,i,i,i,i,i,"Buzz",i,i,i,i)[(i%3<<3)|(i%5)]) for i in range(1,101)])
for i in range(0,101):
if i % 3 = 0:
print “fizz”
elif i % 5 = 0:
print “buzz”
elif i % 3 = 0 and i % 5 = 0:
print “fizzbuzz”
else:
print i
Maybe, it would be beter with the #define’s inside the asm{} block. On my whole operating system, I started with C header files and duplicate ASM declares. Then, I modified my compiler so the ASM could use C struct member names. I then had all the C headers before the asm code. The C headers also had #define’s. That’s why I got in the habit. The #defines could go inside the ASM blocks and might be better.
No conditionals (C):
const char *formats[] = {“%d”, “fizz”, “buzz”, “fizzbuzz”};
for (int i = 1; i <= 100; i++) {
printf(formats[!(i % 3) + 2 * !(i % 5)], i);
printf("\n");
}
@Kyle – Awesome! I love the pattern matching in Haskell
https://gist.github.com/4178709
@Jeremy – Technically those a guard statements and not pattern matching, but they serve much the same purpose. A similar effect could be achieved by removing the guards and adding a case statement. I’ve also seen versions implemented using list expressions, but my Haskell-Fu isn’t strong enough to do one of those properly.
Just for fun, a one-liner in Python 3:
print(*[not x % 15 and 'fizzbuzz\n' or not x % 3 and 'fizz\n' or not x %5 and 'buzz\n' or '%s\n' % x for x in range(1, 101)])
If, and only if, a number is divisible by 3 and 5, it is divisible by 15.
Clive could have saved a lot of time by stopping to consider the problem.
It’s always interesting that whenever FizzBuzz is mentioned, readers always feel obligated to provide their solution. Everybody solves it with a modulus operator. Seems like instead of measuring basic logic understanding, it measures proper use of the modulus operator. Should be called mod-buzz.
I have a number of solutions, 37 in C:
https://github.com/Keith-S-Thompson/fizzbuzz-c
and 49 in multiple language:
https://github.com/Keith-S-Thompson/fizzbuzz-polyglot
(Yes, I really did use Duff’s Device in a couple of the C solutions.)
Too much free time on my hands? Yeah.
functional solution in JavaScript
var three = cycle(['', '', 'fizz'])
var five = cycle(['', '', '', '', 'buzz'])
var fizzbuzz = zipWith(function (a, b) {
return a + b }, three, five)
take(100, fizzbuzz)
javascript
function doFizzBuzz(start, end){
start = start || 1;
end = end || 100;
if(start > end)
return;
for(var i=start; i<=end; i++)
{
var val = "";
if(i%3 === 0)
{
val = "Fizz";
}
if(i%5 === 0)
{
val = val+"Buzz";
}
if(val.length === 0)
{
val = i;
}
console.log(val);
}
}
doFizzBuzz();
@Jeremy Merritt
> I posed a challenge to some coder
> friends to implement FizzBuzz *without*
> using IF statements. Here is my solution:
> http://jsfiddle.net/jeremyx/WD9hF/
that’s not really avoiding IF statements. you avoid the keyword IF, but you use functions like filter which very obviously use IF
@Larry Battle
> @Jeremy Merritt
> Here’s my FizzBuzz solution in javascript
> without if conditions.
> http://bateru.com/news/2012/10/code-of-the-day-fizzbuzz-in-javascript/
that uses ternaries, which may as well be IFs
however, it is possible to avoid IFs completely. @Devin Lane is arguably correct, but his solution depends on parts of printf which cannot be implemented without IF (I have no proof of this, but it seems unlikely).
Here’s my solution which only uses printf for its ability to convert ints to strings and print them rather than to change the behavior of the function using dynamic format strings.
http://pastebin.com/Gmx8RpF8
I can’t think of a way to do it without gotos though.
I’ve had these on my mind for a while now…
both one-liners are in javascript
1. [ 'fizz' ][ x ] // returns fizz if x ==0 else undefined
for(var i=1,j=101,x=['Fizz','Buzz'];i<j;console.log([x[0]+x[1]][i%15]||[x[1]][i%5]||[x[0]][i%3]||i),i++);
2. create array of 101 undefined values, covert obj to str using (""+), conversion gives you a string with 101 commas (which i though was quite funny), split the string and use native foreach where x is the value (we overwrite it in this case) and y is the current index.
note: Array(101).foreach 0&&console.log([x[0]+x[1]][y%15]||[x[1]][y%5]||[x[0]][y%3]||y);})
sorry the last one seems cut off from some reason.
(”+Array(101)).split(‘,’).forEach(function(x,y){x=['Fizz','Buzz'];y>0&&console.log([x[0]+x[1]][y%15]||[x[1]][y%5]||[x[0]][y%3]||y);})
c (without using %d in a format string)
#include // math
void fizzbuzz(int range) {
int i;
char w[3][5] = {“”, “fizz”, “buzz”};
char *s;
for (i = 1; i <= range; i++) {
int num_digits = (int) floor(log10(i)) + 1;
int f = !(i % 3);
int b = !(i % 5);
int p = f | b;
int j;
s = malloc(num_digits * !p + 1);
for (j = 0; j < (!p * num_digits); j++) {
int digit = (i / ((int) pow(10, j))) % 10;
s[num_digits - j - 1] = (char) digit + '0';
}
s[(num_digits + 1) * !p] = '';
printf("%s%s%s\n", s, w[f], w[b << 1]);
free(s);
}
}
Adrusi: here’s a solution without any branch statements in the compiled code* that doesn’t use gotos:
http://pastebin.com/WkKxakpG
(hint: function pointers)
* Requires compilation with -O2, otherwise it ends up with a useless je instruction.
Steve,
I’m sure it’s an honest mistake, but your Gist actually only does the FizzBuzz from 1 to 15, not from 1 to 100 ;)
@Martin May, oops thanks for pointing that out, fixed now! ;)
This situation reminds me of another. I am an engineer, and in college my roommate was an English major. She took a class in non-math based physics, and I found helping her with her homework to be one of the most difficult things I’ve encountered. It’s amazing how much it makes you think about what you really know when trying to view it from a non-technical viewpoint.
Python one-liner:
print “\n”.join((“fizz” * (x % 3 == 0) + “buzz” * (x % 5 == 0) or str(x)) for x in xrange(1,101))
Ahh.. This non-coder’s algorithm, recalls Push Down Automaton and computer science classes to me :)
In PHP:
for ($i = 1; $i < 101; $i++) {
$out = $i;
$out = (($i % 3) == 0 && ($i % 5) == 0) ? "fizzbuzz" : (( ($i % 3) == 0) ? "fizz" : ((($i % 5) == 0) ? "buzz" : $out ));
echo $out. "\n";
}
Scurvy: your solution sucks – you’re not a coder!
The logical test would never test the fizzbuzz part!
Hey Steve!
I’ll share a dirty secret – ever since I came across Pythonic Java I’ve secretly wanted to write something in it. Here’s my entry :-)
https://gist.github.com/4188976
/* 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”.
Pythonic Java – https://gist.github.com/1725650
*/
public class FizzBuzz {
public static void main(String[] args) {
for(int i=1; i<=100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz") ;}
else if(i % 3 == 0) {
System.out.println("Fizz") ;}
else if(i % 5 == 0) {
System.out.println("Buzz") ;}
else {
System.out.println(i) ;}}}}
Hi all (especially Ollie!)
Clive here – Steve’s non-programmer colleague and the guy who tried FizzBuzz on the piece of paper.
I just wanted to respond to Steve’s remark about iteration, and the fact I didn’t just produce the numbers 1 to 100, then apply the fizzes, buzzes and fizzbuzzes as appropriate.
The exercise reminded me of some kind of in-the-round drinking game, where everyone is determining the responses one by one, as an iteration of the last number. Consequently, this shaped the way I approached the problem.
In retrospect, I completely see that I would have been better off simply counting from 1 to 100, then translating each of the 100 numbers into how it should be displayed (Fizz, Buzz, FizzBuzz or as a number). But recreating the drinking game in my head, it made perfect sense to me that each number is determined by being an iteration of the last one. That feels to me like I count in real life.
No recursive solutions so far? In no particular language:
function fizzbuzz( i, max ) {
if ( i <= max ) {
if ( i % 15 == 0 ) {
print 'FizzBuzz'
} else if ( i % 5 == 0 ) {
print 'Buzz'
} else if ( i % 3 == ) {
print 'Fizz'
} else {
print i
}
fizzbuzz( i + 1, max )
}
}
Just because you can. :)
Hah – I can do that without if’s :)
for (i=1; i<101; i++) {
jQuery('’ + i + ”).appendTo(‘.list’);
}
jQuery(‘li:nth-child(3n)’).html(‘Fizz’);
jQuery(‘li:nth-child(5n)’).html(‘Buzz’);
jQuery(‘li:nth-child(15n)’).html(‘FizzBuzz’);
http://jsfiddle.net/P3gZY/
@qxcv
> Adrusi: here’s a solution without any
> branch statements in the compiled code*
> that doesn’t use gotos:
> http://pastebin.com/WkKxakpG
> (hint: function pointers)
> * Requires compilation with -O2, otherwise
> it ends up with a useless je instruction.
I like this solutions. its still tail calls and pointers to labels, which means it’s pretty much the same thing, but it avoids people yelling at you for using goto and is arguably more readable.
Darn it – I’ve just spent nearly 30 mins doing this and then I realise you’re all coders, but here’s my contribution for what it’s worth. It was harder then I thought it would be when I started – this assumes it works..?
Surprisingly after so many years, this question is still relevant in programming.
One Trackback
[...] November 2003 (1) < Previous [...]