jump to navigation

Using FizzBuzz to Find Developers who Grok Coding January 24, 2007

Posted by Imran Ghory in job interviews, Software development.
trackback

On occasion you meet a developer who seems like a solid programmer. They know their theory, they know their language. They can have a reasonable conversation about programming. But once it comes down to actually producing code they just don’t seem to be able to do it well.

You would probably think they’re a good developer if you’ld never seen them code. This is why you have to ask people to write code for you if you really want to see how good they are. It doesn’t matter if their CV looks great or they talk a great talk. If they can’t write code well you probably don’t want them on your team.

After a fair bit of trial and error I’ve come to discover that people who struggle to code don’t just struggle on big problems, or even smallish problems (i.e. write a implementation of a linked list). They struggle with tiny problems.

So I set out to develop questions that can identify this kind of developer and came up with a class of questions I call “FizzBuzz Questions” named after a game children often play (or are made to play) in schools in the UK.

In this game a group of children sit around in a group and say each number in sequence, except if the number is a multiple of three (in which case they say “Fizz”) or five (when they say “Buzz”). If a number is a multiple of both three and five they have to say “Fizz-Buzz”.

An example of a Fizz-Buzz question is the following:

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

Most good programmers should be able to write out on paper a program which does this in a under a couple of minutes.

Want to know something scary ? – the majority of comp sci graduates can’t. I’ve also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution.

I’m not saying these people can’t write good code, but to do so they’ll take a lot longer to ship it. And in a business environment that’s exactly what you don’t want.

This sort of question won’t identify great programmers, but it will identify the weak ones. And that’s definitely a step in the right direction.

About these ads

Comments»

1. Monkeyget - January 24, 2007

I have asked a fizzbuzz question recently. The position was for a .NET developer.
I asked a candidate who claimed to have “one year of experience in .NET” to create the simplest thing I could think of: an application that takes two number and displays the sum of them.
It took five minuts and a bit of my help just to create a new project, as much time to create the visual aspect of the window (drag and drop 2 textbox and a button!) and in the end it didn’t even compiled.

Actually I don’t think asking a “Fizz-Buzz” question is a good thing and I wouldn’t recommend on doing it. I only did it because I knew the candidate wasn’t worth it and wanted to demonstrate it to the boss which had no technical knowledge and therefore couldn’t understand that not knowing what an interface is and not being able to describe what a class and an object are, is a big no-no.
As you said, you still don’t know if he can write good code. You only know that he/she can write the most basic code but you lost some precious time for the interview. Is it worth it? Maybe asking to design and write something more complicate but not that complicate would be better.

Every company worth a damn and caring about who they are hiring : http://weblog.raganwald.com/2006/07/hiring-juggler_02.html

Johnny - December 24, 2012

The problem:

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

A solution doing exactly what was specified in the order it was specified, and avoiding excessive division (no modulo 15 test):

for( int i=1; i<=100; ++i ){
bool modThree = ( i % 3 ? true : false );
bool modFive = ( i % 5 ? true : false );
if( !modThree && !modFive ){
print i;
}else{
if( modThree ) print "Fizz";
if( modFive ) print "Buzz";
}
}

The booleans/ternary are just for readability but could of course also be solved with ints and "== 0" checks.

Johnny - December 24, 2012

The problem:

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

A solution doing exactly what was specified in the order it was specified, and avoiding excessive division (no modulo 15 test):

for( int i=1; i<=100; ++i ){
.bool modThree = ( i % 3 == 0 ? true : false );
.bool modFive = ( i % 5 == 0 ? true : false );
.if( !modThree && !modFive ){
..print i;
.}else{
..if( modThree ) print "Fizz";
..if( modFive ) print "Buzz";
.}
}

The booleans/ternary are just for readability but could of course also be solved with ints as follows (note how hard to read it becomes when you throw away the booleans and have to resort to either ugly "== 0" checks or (even worse) implicit checks below where you are treating the integers like booleans):

for( int i=1; i<=100; ++i ){
.int modThree = i % 3;
.int modFive = i % 5;
.if( modThree && modFive ){
..print i; // neither divisible by 3 nor 5
.}else{
..if( !modThree ) print "Fizz";
..if( !modFive ) print "Buzz";
.}
}

Gib - August 24, 2013

//I would write something lke this
public class FizzBuzz {
public static void main(String[] args) {
for(int i=1;i<=100;i++) {
if(i%3==0) {
System.out.println("Fizz");
continue;
}
else if(i%5==0) {
System.out.println("Buzz");
continue;
}
else if(i%3==0&&i%5==0){
System.out.println("FizzBuzz");
continue;
}
System.out.println(i);
}
}
}

elmysterio - August 28, 2013

This does not work. You will never get FizzBuzz printed.

Tom Guilleaume - December 24, 2013

Am I the only one that would use two independent if statements?


if (i % 3 == 0){
echo ‘Fizz';
}
if (i % 5 == 0){
echo ‘Buzz';
}

So if both are true, it will print “FizzBuzz” and augment the two strings….

2. Lionel Barret - January 24, 2007

Indeed, such an abysmal level of coding skill is simply unbelievable…
I am speechless…

Frankly, i have never seen candidate so unskilled, but in France, comp.sci is really math heavy and I suppose that’s a good filter.

But still…

3. Jacob - January 24, 2007

Want another good filter? This surprised me, but turns out to be a good indication of whether someone has actually ever programmed before.

Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.

If they don’t *start* with creating a third variable, you can pretty much write that person off. I’ve found that I can cut a third to half my (admittedly at that point unscreened) applicants with that question alone.

Derek Clarke - July 5, 2009

There’s an algorithm to do that without a third variable.

int a = 5;
int b = 13;
a = a+b;
b = a-b; //b now has original value of a
a = a-b; //a now has original value of b

Dave - July 14, 2009

But a third variable doesn’t bring in extra testing & debugging costs when a or b get close to MAX_INT.

Waldemar Sauer - July 22, 2009

MAX_INT is not relevant. If a and b are > MAX_INT/2, then a=a+b will cause an add carry. The final a=a-b will cause a subtract borrow. In both cases, the carry and borrow bits are discarded. Derek’s solution is still good.

Dave D - November 5, 2009

A better algorithm without a third variable just uses xor. No max_int problems would occur then:

a ^= b;
b ^= a;
a ^= b;

No third variable and the values are swapped.

Szymon - January 7, 2010

Or even shorter way of doing this in C:

a ^= b ^= a ^= b;

Wojski - January 7, 2010

I don’t see the point in avoiding the third variable.. Compiler will do it’s optimizations and the result will be same in both cases but the person who will look into your code later will have to brain what’s that trick with add and sub for… Isn’t it right?

Tom - January 23, 2010

This is one of the “super smart” bit tricks that fails mysteriously under some non-obvious or unanticipated conditions. Proposing such a thing should disqualify an applicant right away.

In particular the variant proposed by Dave D is well-known for its catastrophic failure if A == B. Derek’s version isn’t free of issues either.

Such “smart” tricks cost software companies many thousands of dollars every year because someone has to waste days or weeks debugging only to find out that a random null-pointer crash at some entirely unrelated place or a totally impossible miscalculation has its root in a “optimized super smart” piece of shit code which not only is less readable and runs much slower than straight code, but also is non-portable and has non-obvious or unpredictable or undefined behaviours

Roberto Simoni - March 29, 2010

And the “readability”?

CJ - August 16, 2010

I think that Jacob’s comment still stands. Programming is a write-once read-many activity, and unless you get some serious performance gains (and only if performance is critical), you don’t want to hire someone that habitually goes for these types of solutions first. Just because there is a way to do it (and in this case an incorrect, unsafe way that requires additional bounds testing) doesn’t mean that you should.

Dan Quellhorst - September 18, 2010

In ruby with no 3rd variable:
a=5
b=13
a,b=b,a

Kam - December 21, 2010

anyone who proposes such a solution had BETTER be talking about running out of registers… If you propose the HARD way, know when to use it!

Barry - March 10, 2011

Tom – Why does Dave D’s (or Szymon’s) fail “catastrophically” if A == B? Suppose a and b are both 100.

a ^= b (a is now 0)
b ^= a (b ^= 0, so b remains unchanged at 100)
a ^= b (a = 0 ^ 100, so a = 100)

Swap succeeds! In any case you can check for equality first:

(a ^ b) && (a ^= b ^= a ^= b)

Reza - April 4, 2011

the question was to swap 2 variables. can’t assume (i wouldn’t assume) the variables are holding integers; e.g. a and b could be strings or objects. so, clever algo, but the question remains good and the right answer has a 3rd variable.

eee_eff - April 9, 2011

You have actually created a third variable, although you haven’t explicitly identified it as such (a+b)

Sanjeev Tripurari - May 9, 2011

I dont say its brainy for choosing a candidate who swaps without third variable.
Think logical, do we really need to do this way.

Its a puzzle, if you talk about programming, the clean way is use the third variable, and good indentation and comments.

Think big problems, if the candidate tries more than one method he sure will write better as he thinks possibilities.

If you get all your answers right in one go, may be he is good in puzzle or had practiced similar.

Alex - September 25, 2012

I don’t see any specification anywhere that two variables are of integral type. What if they are strings? Floating points? Structures? This hacky-tricky way of swapping two integers is nothing more than puzzle. Such solution does not improve performance, not readability.

patrickschluter57 - April 3, 2013

@szymon. Your line a ^= b ^= a ^= b; is undefined behavior. There’s no sequence point between the assigning operators, which means the compiler can update the vars in any order it pleases.
@Derek Clarke
signed overflow is also undefined behaviour. There are several embedded processors where it can fail.
@Tom The catastrophic failure of the xor swap is not when the vars are equals, but when one uses the XORswap in a function with pointers and the pointers are aliases to the same var. Then the variable is zeroed instead of being unchanged.
The XOR swap has furthermore another flaw, they are interdepend instructions and can not benefit from out-of-order execution, the variant with a variable can be issued to 2 pipelines and will internally only have the effect of renaming 2 hardware register.

deminthon - April 6, 2013

“MAX_INT is not relevant. If a and b are > MAX_INT/2, then a=a+b will cause an add carry. ”

You hope … but the C standard doesn’t define the result.

deminthon - April 6, 2013

“In particular the variant proposed by Dave D is well-known for its catastrophic failure if A == B. ”

Utter rot. I would never hire anyone who thinks that could fail, as they have no mathematical intuition. If a == b, then
a ^= b -> a = 0
b^= a -> no change
a^= b -> a = b

deminthon - April 6, 2013

“Your line a ^= b ^= a ^= b; is undefined behavior. There’s no sequence point between the assigning operators”

You, like Tom, have no idea what you’re talking about. This is equivalent to a = a ^ (b = b ^ (a = a ^ b)) … it’s entirely well defined.

Chris Kerlin - April 30, 2013

But all solutions require some kind of additional anonymous storage, whether it is a register, accumulator, stack or data structure.

In perl (as with ruby, Dan) there’s this:

($a, $b) = ($b, $a);

And here’s another:

my $a = ‘water';
my $b = ‘wine';

$a = { a => $a, b => $b };
$b = $a->{a};
$a = $a->{b};

andrewclarkeau - June 13, 2013

You people thinking the comment about A == B are not quite understanding. That’s not a C-language == but the writer was trying to suggest that A IS B – you know, effectively aliases whatever language you are using and how that might happen.

Let me illustrate in plain old C. The fault happens with the +/- solution or the xor solution. The fault happens whether you use C++ references or just plain old pointers.

void swap(int *a, int *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

int x = 10, y = 20;
swap(&x, &y);
printf(“%d %d\n”, x, y);
swap(&x, &x);
printf(“%d\n”, x); /* Oh CRAP */

If you think the use of my swap answer is contrived, consider using the swap function to move things around in an array. I’m sure you’ll be able to come up with a case where [i] and [j] might catastrophically meet in the middle…

andrewclarkeau - June 13, 2013

Damn, noticed a grammatical error. How do you edit these comments? No? too bad… And how do I do markup??

Also, I should point out that if you don’t even use a specific swap() function but write the code inline, your a’s and b’s could easily be

A[i] ^= A[j];
A[j] ^= A[i];
A[i] ^= A[j];

and if ever i and j happen to occupy the same space at the same time you’ll have an Oh CRAP moment again.

Summary: smart-arse solutions will bite you in the bum.

Do you think I qualify for this mythical job the original article was about?

Sam - October 13, 2013

“You, like Tom, have no idea what you’re talking about. This is equivalent to a = a ^ (b = b ^ (a = a ^ b)) … it’s entirely well defined.”

Still undefined behavior. Parenthesis and simple assignments are not sequence points.

jose - November 5, 2013

This laptop only has 8Gb RAM, God knows I might run out of memory if I use one more variable.

Clinton - July 24, 2009

He didn’t say those variables contained integers, or in what language. For all you know they’re DateTime values in C# or blessed references in Perl.

Celestine - November 3, 2009

Was going 2 point that out… Are all variables integer for heaven’s sake? Even if they were, neat codes are highly appreciated.

Edgar Klerks - January 11, 2010

If it a list, I can do this too, haskell code:

import Data.List

(-:) ::(Eq a) => [a] -> [a] -> [a]
a -: b = filter (\x -> x `notElem` b) a

swap :: (Eq a) => ([a],[a]) -> ([a],[a])
swap (a,b) = ((a ++ b) -: a, (a ++ b) -: b)

*Main> swap ([4,1],[2,5])
([2,5],[4,1])

Haakon - December 8, 2009

You can do this in Python without the third variable.
I can’t remember the syntax, and I’m not a CS major yet, but this might just be because they think in Python.

Also, FizzBuzz in swi-prolog, because the world has too little prolog:

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

fizzbuzz(100):-
write(100).
fizzbuzz(X):-
X < 100,
is(Var3, mod(X,3)),
is(Var5, mod(X,5)),
;(
(
==(Var3, 0),
==(Var5, 0),
write('Fizz Buzz'),
nl
)
,
(
;(
(
==(Var3,0),
write('Fizz'),
nl
)
,
(
;(
(
==(Var5,0),
write('Buzz'),
nl
)
,
(
write(X),
nl
)
)
)
)
)
),
is(Y, +(X,1)),
fizzbuzz(Y).

If anyone has any improvements to offer, send me a mail or something. :D

Narayan Ramchandani - December 9, 2009

Hi, Just my 2 bits on my PHP based “FizzBuzz” solution, just a little shorter. I love ternary operators.

for ($i=1;$i$val)
{
echo “[".($key+1)."] “.$val.””;
}

Narayan Ramchandani - December 9, 2009

Hi, Just my 2 bits on my PHP based “FizzBuzz” solution, just a little shorter. I love ternary operators. Don’t know why the site showed only half of my code earlier.

//Program start
for ($i=1;$i$val)
{
echo “[".($key+1)."] “.$val.””;
}
//Program end

Merwok - January 2, 2010

This is how Python does it:
a, b = b, a

tradjick - July 1, 2010

My versions
in php:

list($b,$a)=array($a,$b);

…and for fizzbang:
for ($x=1;$x<=100;$x++) echo (($f3=$x%3)?'':'fizz').(($f5=$x%5)?'':'buzz').(!(!$f3||!$f5)?$x:'');

dutiona - May 9, 2013

Hey,

Another prolog version :p

loop(N) :- N = 101.
loop(N) :- N rem 15 =:= 0, write(‘ FizzBuzz’), nl, A is N + 1, loop(A).
loop(N) :- N rem 3 =:= 0, write(‘ Fizz’), nl, A is N + 1, loop(A).
loop(N) :- N rem 5 =:= 0, write(‘ Buzz’), nl, A is N + 1, loop(A).
loop(N) :- write(N), nl, A is N + 1, loop(A).

loop(1).

Brian Knoblauch - March 9, 2010

I’m sorry that it’s not so easy for you high-level programmers. Us low-level assembly guys can usually do it without a temp variable (given the right constraints).

“xchg ax, bx”

Done. :-) (Does require at least one to be in a register, but hey, C guys use register vars all the time!).

ari-free - February 7, 2011

I’m not a CS graduate. I just finished chapter 6 in Starting out with C++ by Gaddis:

C++ (indenting may be off but that’s why I don’t use python…)

int main()
{
int num;
const int FIZZ=3, BUZZ=5, FIZZBUZZ=15;
// FIZZBUZZ is a multiple of FIZZ and BUZZ

for (int i=1; i <= 100; i++)
{
num = i;
if (! (i % FIZZBUZZ) )
{
cout << "FizzBuzz" << endl;
} // if (! (i % FIZZBUZZ) )

else if (! (i % FIZZ) )
{
cout << "Fizz" << endl;
} // if (! (i % FIZZ) )

else if (! (i % BUZZ) )
{
cout << "Buzz" << endl;
} // if (! (i % BUZZ) )

else
{
cout << num << endl;
} // else

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

return 0;

} // int main()

Sandro Pasquali - March 3, 2012

What if the language used supports destructuring assignment?

Jennifer Sanders - June 10, 2012

a,b = b,a

Python!

Doug Hoffman - October 8, 2012

a b to a to b

Forth!

Cat Enthusiast - October 27, 2012

(\(a,b) -> (b,a))

Haskell!

Aaron Swenson - May 8, 2013

($a, $b) = ($b, $a)

Perl!

Brian - June 20, 2013

One of the things that intrigues me from these clever responses is that the authors trade a temporary variable for extraneous arithmetic operations. In other words, their excessive cleverness results in less efficient code. Personally, I subscribe to the principle of making it good first (functional, readable) and then making it fast only as required.

Even using 2 temporary variables could produce code that is more efficient than these clever responses. Consider that many processors do not have memory-to-memory store instructions. If the two variables are in memory, or if function parameters are passed on the stack, the following instructions

t = a;
a = b;
b = t;

May actually be implemented as

r1 = a;
r2 = b;
a = r2;
b = r1;

I’m with Jacob and CJ on this one. I don’t need any more excessively-clever programmers on my team. I need competent engineers who write accurate, readable and maintainable code. In the end, customers don’t care about cleverness, they want something that works well.

Rod - June 29, 2013

In ALGOL on MCP systems, you don’t need a third variable or any special tricks; you use the “swap” operator: “A :=: B;”

Chris - July 2, 2013

How do you do that if the variables are strings without using a temp variable like below.

private void Swapping3(T a, T b)
{
T temp = a;
a = b;
b = temp;

Console.WriteLine(“Now: A = {0}, B = {1}”, a, b);
Console.Read();
}

Gib - August 24, 2013

public class SwapNum {
public static void main(String[] args) {
int a = 40;
int b = 20;
boolean temp = (a > b) ? true : false;

System.out.println(“The numbers are :”+a+” “+b);
if(temp) {
System.out.println(“Swapped is :”+b+” “+a);
}
else System.out.println(“Swapped is :”+b+” “+a);
}
}

4. Mitch Silverman - January 24, 2007

I once worked at a company that did a lot of geometric computations. Our standard interview question (to be done as homework between interview 1 and interview 2) was write a function in c that would “Chord” a circle to an arbitrary level of precision. Inputs were radius and tolerance. Output was the number of sections needed to break up the circle.
In the second interview we would review the code and talk about error catching, what happens when radius is less than distol.. etc.
But the trick was when we asked for a function to do the same thing with an ellipse. We didnt want an answer – we were looking for the response
Was the candidate excited? Thoughtful? or did (s)he get that deer in the taillights look in his/her eyes?

5. Ben Prew - January 24, 2007

Jacob,

There are several languages that you can do this in that don’t require a temporary variable. I know Perl supports this, and I believe Ruby does as well:

ex.

($a, $b) = ($b, $a)

I’m not sure about Python or other dynamic languages, but I believe they do.

Finally, you can do it in C as well:

void XORSwap(void *x, void *y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}

I’m assuming that you’re eliminating candidates who actually can’t get swap() correct. But, in several cases, not starting by creating a temporary variable is actually a good thing :)

Billy O'Neal - April 23, 2010

“Finally, you can do it in C as well:”
That is invalid. You can’t dereference a void pointer.

Tony - November 7, 2010

That’s what I was thinking. How does the compiler know how bytes of data a void * points to?

Alex - September 26, 2012

I would not be surprized if ($a,$b) = ($b,$a) internally ended up in TWO temporary variables.

gallier2 - April 3, 2013

There’s another problem with the C variant and that is what the “catastrophic failure” Tom was aluding to above. If the pointers are aliases, you wipe out the vars. If you call XORSwap(&v, &v), the result will be 0, not the value v had before.

6. Alexandre Vassalotti - January 25, 2007

“Want to know something scary ? – the majority of comp sci graduates can’t.”

That is indeed scary. I have a hard time to believe it. Maybe, the candidates were thinking it was a trick question or something like that. I don’t know.

I took me less than 1 min (I timed myself), to write the correct solution and never taken any course. Now, I’m wandering what they teach in Computer Science courses.

# Fizz-Buzz in Python
for i in range(1, 100):
if (i % 3 == 0) and (i % 5 == 0):
print “FizzBuzz”
elif i % 3 == 0:
print “Fizz”
elif i % 5 == 0:
print “Buzz”
else:
print i

# Swap in Python
a = 0
b = 1
b, a = a, b

Personally, I would ask them, as a weeder question, to write a function that sums up integers from a text file, one int per line.

Gerry - February 25, 2010

I’d ask you to write it again in a way that’s efficient and easier to maintain. :P

Luke - June 21, 2013

for x in xrange(1, 101):
to_print = ”
if x % 3 == 0:
to_print += ‘Fizz’
if x % 5 == 0:
to_print += ‘Buzz’

if not len(to_print):
to_print = x

print to_print

Conrad - March 1, 2010

Er, I believe that does not include 100 (1 to 99) :P

markc86 - March 11, 2010

Yes, but you could say the wording is unclear, as opposed to “1 to 100 inclusive”.

Bistole - September 14, 2010

You don’t have to have the ‘print “FizzBuzz”‘ line and it’s corresponding condition, just make the elif’s into if statements.

Mark C - September 24, 2010

You know, I was thinking about this problem while reading a StackOverflow question, and realized the same thing.

blahedo - October 16, 2010

Nope, that won’t work. Or rather, if you do that, you need to add a condition to the final “else”, because the number should only print if *neither* condition applies.

L. - December 1, 2011

Err . you’re fired dude .

Not understanding halfway through the problem that doing an additional (here double) check everytime is bad … fired.

mod 3 = 0 -> fizz
mod 5 = 0 -> buzz

That’s it.

Everytime it’s looped you get two checks (that sucks but unfortunately there is no better way) .
total : 200 checks

But in your case …

6 if mod3 mod 5 -> 6*2 checks
33-6 if mod 3 -> 27*3 checks
20-6 if mod 5 -> 14*4 checks
53 match nothing -> 53*4 checks

total : 12+81+56+212 checks = over 50% more for no reason.

So basically you have no logic and should not code anything because you do not understand how the machine works. at all.

And thus fail to translate “human requirements” into “logic”.

L. - December 1, 2011

Meh . nothing like major fail .
add :
if(echo not empty) string.=’-‘
inside the if mod5 part
that’s another check . still faster but hey . not that much . still more logical though.

L. - December 2, 2011

So if it really is fizzbuzz and not fizz-buzz . above option is like 161 less checks and much simpler anyway. sounds good to me.
{
$echo=$i;
if($i%3==0){echo $fizz;$echo=””;}
if($i%5==0){echo $buzz;$echo=””;}
echo $echo;
$i++;
}
I suspect a variable assignment has to be a few times cheaper than a check … anyone know of a good resource for that kind of information ?

qbj - May 8, 2013

I feel silly replying to a one and a half year old comment! But your reply was to a three year old one, so I guess I’ll go ahead.

No, I’m sorry, you’re the one that’s fired. I’m not just saying that for dramatic effect because it’s what you said. Trying to optimize everything is such a basic mistake (ranking up with putting inheritance everywhere because it “makes everything more generic”) it is really unforgivable in an interview, even for a junior programmer. It’s a fact that’s usually covered over and over in software engineering modules. Type “premature optimization” into Google and it will helpfully suggest “is the root of all evil” for you… you don’t even need to press enter!

There are so many arguments about why you shouldn’t optimise early that I could hardly hope to fit them into this comment. I think the most important are:

1. When a program (or service, or whatever) runs too slowly, it’s almost always because of the overall design, rather than because the way the individual bits of code were written is too slow.

2. Even when 1. doesn’t apply, it’s not the case that to get a 20% speedup you need to get all the code to go 20% faster. Instead there will turn out to be one or two critical paths that need optimising.

3. Why not just optimise everything just in case? Aside from the expense (extra thought from programmers costs time and therefore money), making optimisations makes code less clear. This is the main issue: BUGS. Small chunks of code are thousands or even tens of thousands of times more likely to contain a bug than to end up being a critical slowdown. This is the case you need to target, by writing code that is as readable as possible, even if you know that you’re testing a variable unnecessarily in every loop iteration or whatever.

The thing that’s particularly funny about your post is that you’re fretting about a loop that has 100 iterations. You even carefully break down the numbers, complaining about 100 odd too many checks. This is another classic sign of a rooky: they think that 100 (or even 1000) is a big number to a computer. You’re saying this guy is fired because his program – which is presumably only meant to run once – takes a ten millionth of a second too long!?

After being so very wrong, you follow up your comment with this doozy: “So basically you have no logic and should not code anything because you do not understand how the machine works. at all.” It makes me wonder if I’ve just wasted my time replying to a troll. But there, I’ve typed it now, so I might as well hit submit.

victorbarrantes - March 15, 2013

In python only one print sentence is needed:
for i in range(100):
label = ” #these are 2 single quotes
if (i + 1) % 3 == 0:
label += ‘Fizz’
if (i + 1) % 5 == 0:
label += ‘Buzz’
print(str(i+1) if label == ” else label)

7. Vineet Kumar - January 25, 2007

I was also going to respond to Jacob’s swap question with the python unpacking example, but Ben and Alexandre beat me to it. Though Ben, in your C example, you can’t dereference a void pointer. I wouldn’t say that really falls in the FizzBuzz category, but it would be a minus point for the interviewee.

8. Jos'h - January 25, 2007

“””
fizzbuzz.py
josh 2007-01-25
Print integers 1 to 100. Sub ‘Fizz’ for multiples of 3, ‘Buzz’ for mult of 5.
Sub ‘FizzBuzz’ for mults of both. Written for the purpose of being silly.
“””

threes = range(0, 101, 3)
fives = range(0, 101, 5)

def check(n):
. plain = 1
. if n in threes: print “Fizz”, ; plain = 0
. if n in fives: print “Buzz”,; plain = 0
. if plain: print n,
. print

[check(i) for i in range(1, 101)]

DOko - May 3, 2010

Your program doesn’t perform as per specifications.
It should print Fizz-Buzz, not FizzBuzz.

a - June 4, 2010

re-read them

Ken - August 17, 2010

Way to turn the problem into O(n^2)

Dr. Jarajski - July 7, 2011

Your solution got me giggling like an idiot for a couple minutes.

I’m now trying to make it 0(n³) for kicks.

I’ve always been a fan of retardedly complex solutions to simple problems, maybe because so many of my class mates do this kind of thing inadvertently.

9. Geordan’s Musings » Fizz Buzz - January 25, 2007

[...] came across this post on programming.reddit.com regarding using a very simple exercise to weed out completely inept [...]

10. Mohammed Zainal - January 25, 2007

good post,
i know little programming , learnt by trial & error , internet and books.
i do complicate things while writing my code , prolly because im not really good with math , but yet & the end i’ll find the solution .

candidates some time gets tension during the interview and that will effect the results .

p.s nice blog buddy :)

11. mult.ifario.us : Laziness and fizzbuzz in Haskell - January 25, 2007

[...] peeking at Reg’s solution, I can’t resist posting a fizzbuzz implementation in Haskell (because it looks stylistically like it should be written in an FP [...]

12. flickrhoneys - January 25, 2007

I used to grok coding, but I’ve grown up since then :D

13. Miauw - January 25, 2007

“Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.” (Jacob)

How do you do that in functional languages with single assignment? :)

NPSF3000 - June 19, 2011

In Erlang I’d use recursion :)

Pseudocode:

Swap (x, y){
Swap (y, x, false)
}:

Swap (x, y, false)
{
//Continue as needed.

}

Fairly useless, but technically fulfills requirements.

14. Stephen. - January 25, 2007

Ech, state variables stink. Here’s a better python solution

for i in range(1,100):
fizz = (i % 3 == 0) and “Fizz” or “”
buzz = (i % 5 == 0) and “Buzz” or “”
print “%2i %s%s” % (i,fizz,buzz)

DOko - May 3, 2010

Again with the missing -

mnietek - June 17, 2010

Again you din’t read the requirements. You’ve failed

Stephen M - September 19, 2010

As far as I can tell from the specifications (and to be honest, I think it’s pretty clear) – you do *NOT* print the number if it’s a multiple of 3 or 5! About 1/2 of the solutions here that congratulate themselves on dodging the if/elseif/elseif/else structure tend to print the number out every time around the loop, which is incorrect.

I’d far rather take the if/elseif/elseif/else guy over someone who did not read and understand the specifications properly.

Josh Rehman - April 28, 2012

There is no need for complex if/else. In Java:

public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i < 101; i++) {
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz || buzz) {
System.out.println(i + ":" + (fizz ? "Fizz" : "") + (buzz ? "Buzz" : ""));
}
}
}
}

(This took me 4 minutes from opening Eclipse to execution)

deminthon - April 6, 2013

Josh = fail.

stupid2 - November 11, 2010

the right version: http://codepad.org/qlCgPRaS

15. john cromartie - January 25, 2007

Fizzbuzz in a nasty Ruby one-liner:

puts (1..100).to_a.collect { |i| i % 15 == 0 ? ‘fizzbuzz’ : (i % 5 == 0 ? ‘fizz’ : (i % 3 == 0 ? ‘buzz’ : i)) }.join(‘ ‘)

Javier Vázquez Rodriguez - June 13, 2010

No need to make an Array out of the Range, that makes it even nastier:

puts (1..100).collect{|i|i%3==0?i%5==0?”FizzBuzz”:”Buzz”:i%5==0?”Fizz”:i}
:)

16. john cromartie - January 25, 2007

“How do you do that in functional languages with single assignment? ” (Miauw)

You wouldn’t have variables to begin with… unless it was a monad, in which case you would just do it the normal way.

17. Joshua - January 25, 2007

Java:
public static void main(String[] args)
{
for (int i = 1; i

18. Jacob - January 25, 2007

Ben,

I’d take anything that works. If I were interviewing for a C or Perl position, your examples would be fine. The key is to pose the question and observe them tackling it. *How* they tackle it is as important as whether they come up with the “right” answer. My example of swapping the values in two variables is a pretty trivial question, so how long it takes and their approach to doing it is the information I’m parsing, not whether they end up in the right place in the end.

19. sibecker - January 25, 2007

Here it is in functional programming (OCaml):
“How do you do that in functional languages with single assignment? ” (Miauw)

OCaml one liner:

let fb x = (if x mod 3 = 0 then “Fizz” else “”) ^ (if x mod 5 = 0 then “Buzz” else “”) in let fb2 x = let f = fb x in if f = “” then string_of_int x else f in let rec fb_to x = let g = fb2 x in if x = 1 then g else (fb_to (x-1)) ^ “, ” ^ g in fb_to 100;;

deminthon - April 6, 2013

WC = fail.

20. WC - January 25, 2007

def fizzbuzz():
for n in range(1, 101):
str = “”
if not n % 3:
str += “Fizz”
if not n % 5:
str += “Buzz”
print n, str

21. anon for this one - January 25, 2007

Ruby FizzBuzz in 81 bytes. (please let my next employer ask this in an interview… please)

f,b=’fizz’,’buzz’
puts((1..100).to_a.map{|i|i%15==0?f+b:(i%5==0?b:(i%3==0?f:i))})

22. Cale Gibbard - January 25, 2007

Er, what do you mean “the majority of comp sci graduates can’t”? Do you have any data to support that?

At least where I went to uni, not just comp sci graduates, but everyone in first year mathematics had to learn to solve harder programming problems than that. By the end of second year, everyone in comp sci, and a large portion of those in any program in the mathematics faculty will have written a simple compiler. So I don’t see how this problem would be of any difficulty.

I can’t say anything about how typical my university was (in fact, I suspect it’s quite atypical, and I was there for a pure mathematics degree anyway). So sure, this is just one datapoint, but I’m curious about where your conclusions are coming from.

Billy O'Neal - April 23, 2010

I know several comp-sci students at my university that cheat.

23. goblinfactory - January 25, 2007

How about overloading the assignment operator in C#?

moron4hire - February 22, 2010

you can’t, but you can do implicit type conversions

24. Dr Jekyll & Mr Hyde » Blog Archive » FizzBuzz and bored programmers - January 25, 2007

[...] his blog, tickletux advocates the use of FizzBuzz to find developers who grok coding. However, this kind of test may also cause difficulties. What do you do if a candidate answers with [...]

25. azman - January 26, 2007

you’re right about comp sc student didnt rite!
even my friend with master degree in comp science cant even rite “hello world” program!!..hahahah..
nice blog

26. Andrew - January 26, 2007

;; scheme example… though, i’m not happy

(define (fizz-buzz rng)
(let loop ((n 1))
(let ((thr (remainder n 3))
(fiv (remainder n 5)))
(cond
((and (zero? thr) (zero? fiv)) (printf “fizz-buzz~n”))
((zero? thr) (printf “fizz~n”))
((zero? fiv) (printf “buzz~n”))
(else (printf “~a~n” n)))
(if (= rng n)
n
(loop (add1 n))))))

(fizz-buzz 100)

27. Brian Mitchell - January 26, 2007

If you’re going to golf it you might as well check if things like the repetition of values actually helps. Here is something short in ruby.

puts (1..100).map{|i|i%15==0?’FizzBuzz':i%5==0?’Buzz':i%3==0?’Fizz':i}

I’ll also punish anyone on my team who writes a set of nested ternary expressions like that. It’s nice to know those things for golfing games though. ;-)

28. macnod - January 26, 2007

Common Lisp:
(loop for a from 1 to 100 collect
(let ((c (zerop (mod a 3))) (d (zerop (mod a 5))))
(cond ((and c d) “FizzBuzz”)(c “Fizz”)(d “Buzz”)(t a))))

29. Randy - January 26, 2007

Why do people always insist on writing one-liners?

Yes, you may get your rocks off by writing something a litty crazy, but the guy who has to maintain your code, is going to be hating you. Just say no to one-liners. And say yes, to clear, consistent coding.

30. Brian Mitchell - January 26, 2007

Randy, I agree but in this case it looks like it was so easy to solve that people went a little farther and started a game of golf [0].

[0] The original golfing language was perl but it has now become popular way for bored programmers to play with their skills in many different languages.

31. khudari - January 26, 2007

Dave Kaemmer came up with a similar test at Papyrus that I have been using for years.

This kind of test is too simple to measure programming skill, but it is a great predictor of who will be very productive and who will not. We found it much better than a person’s resume, for example. So my technique is to administer the test via email (with a 20 minute time limit) to every applicant after a very basic resume screen. This saves a lot of valuable engineering staff time doing interviews. Our only problem: it is really hard to find candidates we want to interview.

32. George - January 26, 2007

WTF is this on the Daly WTF

33. Jeff Staddon - January 26, 2007

Maybe it’s just economics? With all the technology buzz and high salaries there’s a lot of motivation to jump on board. Especially for a young person who doesn’t really know their strengths/weaknesses. Univ I’m afraid are more interested in selling students on taking classes than on helping these kids find themselves.

All the good developers I’ve known never really choose technology—they were drawn to it as if it were some alien tractor beam. Back in my university years I tried to escape myself–I majored in history–but I couldn’t help but write Perl scripts on the side because it was so much fun! (BTW–anyone else out there majored in history??)

34. Brendan - January 26, 2007

Apologies to Mr. Anon with his 81 bytes, but I did it in ruby in 71.

puts (1..100).map{|i|(s=(i%3==0?’Fizz':”)+(i%5==0?’Buzz':”))==”?i:s}

35. Eric - January 26, 2007

Re: No One Liners

I personally enjoy a challenge as a developer and one liners often provide just that. While it is probably not as helpful to folks maintaining code because it can be confusing, I would rather hire someone who will figure it out and learn something then someone who simply brushes things off as being unclear.

I am not saying folks should write everything on one line, be reducing line counts is a good way to learn details of the language along with different ways of implementing algorithms.

36. Brendan - January 26, 2007

I would certainly not put anything like the above in production code.

However, someone who golfs successfully is someone who also knows the syntax precisely – they know when they can go without parentheses, spaces and the like.

Of course, if someone wrote something like the above in a live interview as a first pass, I don’t know whether I’d be more or less inclined to hire them. After all, I sure don’t think well like that.

37. Reg Braithwaite - January 26, 2007

I think it’s important to avoid overthinking the question and the answer. All you want to do is eliminate the extreme time wasters taht have no clue whatsoever.

The key is that someone solves it in fifteen minutes or less. If they want to Golf with it, or show off the fact that they just read a book about Higher Order Functions, I say don’t mark them down but don’t mark them up either.

Just invite them in for the interview. That’s the place where you can find out f they’re too clever by half, or perhaps they were bored, or are really straightforward but thought they needed to show you something special just to get the job.

http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html

38. Alex - January 27, 2007

Sorry, Ben Prew, but your C solution shouldn’t even compile – I’m afraid you missed the cut for working for tickletux! :)

> void XORSwap(void *x, void *y)
> … dereferencing “void *” …

39. lev radin - January 27, 2007

It seems to me weird that in blog based on PHP nobody offered way how to swap variable in PHP. Here you go:
list($a,$b) = array($b,$a);

40. Philip Munce - January 27, 2007

Not a bad test. Although I sometimes wonder if a dev team needs a couple of guys who can’t code. Reason being is that unless you work for a startup most dev work is repeatative and simple like HTML wording changes. Just the thing for someone who doesn’t know how to go to google and type “how to use modulus arithmetic in “.

41. hairmare - January 27, 2007

crappy code, but written in the time constraints. i actually get the shivers when i see courses like programming HTML on comp sci curriculas. there are also some unis where the industry links are getting to strong and thus hindering real innovation on the merits of making money and protecting IP in new inventions.

42. hairmare - January 27, 2007

$i=1; while ($i

43. Steve Biko - January 27, 2007

Jacob said: “Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.

If they don’t *start* with creating a third variable, you can pretty much write that person off.”

B.S. You can swap the values without a third variable using XOR:

var1 = var1 XOR var2
var2 = var2 XOR var1
var1 = var1 XOR var2

Kam - December 21, 2010

ya, you can. But can yinz answer: why? [performance increase is the natural answer, on contemporary systems. bonus if you can get why on older ones...]

44. Reg Braithwaite - January 28, 2007

Swapping two variables:

The ‘XOR’ thingie is an old C/C++ ‘Aha!’ I’ve never met anyone who figured it out from base principles, everyone seems to have been shown it by someone else.

Nevertheless, it often comes up in C++ interviews and that may not be a bad thing: if you’re a C++ programmer and you’ve never heard of this trick, you probably don’t spend a lot of time actually hanging around other C++ programmers and trading tips (I’m talking to you Mr. “Visual C++ in 21 Days”).

All that being said, the given trick obviously only works in languages where XOR applies to the values given. This will not work with arbitrary Java objects, for example. Although the references might be CPU words, the language won’t let you XOR them or even cast the references to a primitive long.

45. Joshua Volz - January 28, 2007

IMO, it’s not the answer that matters, but the explanation of the answer that they give. If they write something like:

for i in range(1,101):
s = ”
if i % 3 == 0: s = “Fizz”
if i % 5 == 0: s += “Buzz”
if i % 3 != 0 and i % 5 != 0: print i
else: print s

But then told me, “yes, I know I am retesting i in the third clause, but I think it might make the code more understandable,” I would be okay with their answer, especially if they went on to do it in a single liner. I would also accept something like:

for i in range(1,101):
if i % 15 == 0: print “FizzBuzz”
elif i % 3 == 0: print “Fizz”
elif i % 5 == 0: print “Buzz”
else: print i

This at least shows that they realize that if something is divisible by 3 and 5, then it is also divisible by 15 (not a mind-bending fact, but at least they are changing the problem to be expressed without using “not”).

The follow-up question from the interviewer is what is important. If they give either of the previous two solutions (or something similar), and then you ask them to optimize for length of code, or execution time (aka “don’t retest”) and they understand what you want, then you are learning something about them. That’s the real goal of the interview.

The deeper question is what does it say about CS education that this is a reasonable test to give someone to find out if they know what they are doing. Anyone who can’t answer this, even under the stress of an interview, isn’t really a programmer. How could you trust someone with hundreds of thousands of lines of code, and the design of classes (usually) when they can’t do this?

Another fun solution, although convoluted:

for x in range(1,101):
a,b=x%3==0,x%5==0
print “%s%s%s”%(a and “Fizz” or ”, \
b and “Buzz” or ”, not a and not b and x or ”)

## I put the ‘\’ in there so that it wouldn’t wrap in the space alloted.

46. Bart Gottschalk - January 29, 2007

Here is an HTML/JavaScript implementation. I do these exercises for fun of them and because I’ve been “promoted” in my career to the point where I don’t get to write much code on the job. Doing exercises like these keeps the mind fresh and allows me to remember what it’s like to write code. Probably took about 5 minutes but that’s because I never try to remember syntax. I just look it up when I need it.

FizzBuzz

//

47. Bart Gottschalk - January 29, 2007

Oops. Let me try posting my JavaScript solution again:

var output = “”;

for( var i = 1; i

48. Tomas - January 29, 2007

Java code snippet:

for(int i=1;i0?toPrint:i);
}

Indeed, we would need to create a whole java class with a main method just to run this.
what a nasty language.

49. Tomas - January 29, 2007

Java code snippet (again):

for(int i=1;i<=100;i++) {
String toPrint=(i%3==0)?”Fizz”:””;
toPrint+=(i%5==0)?”Buzz”:””;
System.out.println(toPrint.size()>0?toPrint:i);
}

Indeed, we would need to create a whole java class with a main method just to run this.

(sorry the duplication. < and > are guilty)

50. Leonardo Herrera - January 30, 2007

Heh, can’t resist.

for(1..100){$t="";$t="Fizz"if!($_%3);$t.="Buzz"if!($_%5);$t||=$_;print"$t\n";}

51. Leonardo Herrera - January 30, 2007

…well, that was a 78 bytes solution that it is now buried under some weird CSS property. Alas.

52. StoneCypher - February 1, 2007

Jacob: most experienced coders use the XOR swap trick instead of allocating a new variable when swapping two machine primitives; it’s generally slightly faster and can be done in registers on the smallest of embedded machines.

If you see someone starting by allocating a third variable, you shouldn’t be hiring them.

Kam - December 21, 2010

Xor takes what, four clock cycles? Memory access takes 100, even from L1…

Seebs - December 10, 2012

I am stunned. This is… well, frankly, stupid. First, the xor swap trick is only relevant in a narrow range of languages. Secondly, it is often gotten wrong; at least one person here posted a form without sequence points, which is wrong. Another posted a form using pointers — but dereferenced void *, which is wrong, and even if you don’t, the pointer version fails if the two pointers are to the same object.

If you’re writing C, and you are trying to outsmart the compiler, you should have retired in the early 90s. Write clear code, and assume that the compiler is probably a little more clear on how the machine works than your vague recollection of what you read about a 6502 once.

53. George - February 2, 2007

Fizzbuzz in forth

: fizz? ( s — f ) 3 mod 0= ;
: buzz? ( s — f ) 5 mod 0= ;
: num? ( s — ) dup fizz? swap buzz? or 0= ;
: ?fizz ( s — ) fizz? if .” Fizz” then ;
: ?buzz ( s — ) buzz? if .” Buzz” then ;
: ?num ( s — ) num? if . then ;
: fizzbuzz ( s — ) dup ?fizz dup ?buzz dup ?num cr ;
: fizzbuzzes ( s — ) cr 1+ 1 do i fizzbuzz loop ;
100 fizzbuzzes
bye

it is fast well factored and with dumb logic no repeated values without return values it did not take two seconds because i was just learning to think forth, but this will

David L. Paktor - March 4, 2014

Hi, George.
Nice but… Your “fizzbuzz ( s — )” is actually “fizzbuzz ( s — s )”
I.e., it leaves its input param on the stack.
You need to either remove the last “dup” or tack on a “drop” (your choice depending on whether you prefer exec speed or symmetry…)
Congrats on learning to “think forth”. I recommend heavy use of stack-diagrams, especially at first. Had you used them in “: fizzbuzz”, the error would have become immediately obvious.

54. George - February 2, 2007

Also at the http://www.jwdt.com/~paysan/why-forth.html it says what discribes a bad programer

A few people expressed doubt if they are bad programmers, or if they shouldn’t try Forth because they might be part of what I considder “bad programmers”, so here’s a small test if you are a bad programmer. The more of the following answers you answer with “yes”, the worse you are. Don’t feel bad if you have a few “yes”, nobody’s perfect. I added also a few questions where a “no” should be quite sure:

* When you program, you wince at least once every minute, and not just because your tool crashed or displayed other bugs, but because you stare a the blank screen and don’t know what to enter.
* Extra points if you avoid this by pretenting to do “design” before coding, and you just produce tons of documents and UML diagrams without ever touching the keyboard and leaving the dirty work of implementing your designs to other people.
* When you have a problem, you invite for a meeting. The more people you invite here, the more points (and pointy hairs) you get.
* You think that a team of 10 programmers can solve tasks 10 times as complex or in one tenth of the time. Bonus points if you think 100 programmers scale as linear. Point dropped if you believe that because a set of 10 programmers contains one which is capable to outperform the average programmer by a factor of 10. Tell me how you prevent the others to mess up the job of the elite one.
* You always ask you what’s so funny about these “Dilbert” strips your coworkers put on their cubicle walls. Extra points if you follow the advices in “Dogberts top secret management handbook” when managing the dolts below you.
* You do programming for money; doing it as a hobby (for fun!) is something that only madmen do.
* You believe that programming can’t be self-taught, and titles are worth more than experience.
* You believe that your self-taught skills are better than anything you can learn at a university. Remove that point here if you believe that because you are the archcancellor of an elite university, and therefore know what you are talking about.
* You can’t grasp how this free software, or as you call it, “Lie-nuts” system came around, other than being either all lies, or created by nuts. Bonus points if you believe both.
* Your programs tend to become an unmaintainable mess of spaghetti code after 1000 lines (add bonus points if you reach that state earlier, reduce if you reach it later, “master of bloatware points” if your programs exceed 100klocs and are still maintainable). Extra points if your programs grow wild even after they have become unmaintainable.
* You didn’t know what to do with these rectangular Lego bricks when you were a child, and rather played with prefabricated toys.
* You think that one programming language (and maybe assembler) is enough to be a competent programmer. Bonus points if you believe that knowing a programming language isn’t necessary at all to be a competent programmer.
* You still believe that if you think hard enough you can produce correct non-trivial code without testing, though testing in the past always proved you wrong.

L. - December 2, 2011

Awesome . Too bad you won’t get honest answers on that cuz it’s pretty much relevant.

I lost a point at “university” though .. I really cannot get my head around the idea that someone in a uni could possibly bring you something MORE important than what you learn facing real problems.

Programming imho :

1. Logic – you can’t make people logical . math n stuff improve your logic level but that’s just it.

2. Abstraction / Visualization (as in in-brain complex system rendering) – noone can teach you that either . a good deal of math.physics will surely help improve, but that’s it.

3. Resource gathering (as in, “we require additional pylons”) – this is more about knowing what tool is suitable for what (i.e. vb/access/mysql = trash, perl = parsing powa, c++/fortran = math speed, python = damn another version still, java = gay syntax ftw, etc.) and mostly have a good ability to guess if something already exists, and if the already existing option/library is too much of a piece of crap to be used – or not.

4. Translation – everyone can learn that and it’s pretty much nothing special, also called “coding” or “writing code” or stuff. Now memory will surely help on that, and that can be trained as well so yeah . important and required it is .. but it’s something anyone can do without too much training (you know, writing if then else doesn’t require much brains . avoiding those two useless checks for every loop because you want to do something different for 1st and last element of a collection … is a step in the right direction).

5. Profit !

As a summary, I believe one should never underestimate what someone or something can teach them (be it some dude or the uni), but none of these potential learning sources should be glorified to the point of causing negative points in your scoring of me.

55. Patrick - February 5, 2007

Who says there is no ternary in python?

print “\n”.join([str(not (i%3 or i%5) and "FizzBuzz" or not i%3 and "Fizz" or not i%5 and "Buzz" or i) for i in range(1, 101)])
;-)

56. Ralph Miner - February 6, 2007

How disappointing that not one of the solutions fro Fizz Buzz started with writing acceptance tests.

57. What Do Programmers Do? » Continuous Learning - February 12, 2007

[...] Imran says many programmers can’t write code: [...]

58. Tragomaskhalos - February 13, 2007

The FizzBuzz program is a lovely little test, and I’ve now used it a couple of times myself in interviews. One guy got a “7/10″ from the business folks interviewing him, had 2+ years of Java on his CV, but couldn’t do this challenge at all – I mean he took a few minutes to even get out the loop opening, and that was a weird mishmash of while and for syntax.
I’d hate interviewers to dismiss this test as being too easy – in my experience it is genuinely astonishing how many candidates are incapable of the simplest programming tasks.

59. Cameron Kerr - February 24, 2007

Remove the leading ‘. ‘ on each line to use. Haskell is indent-sensitive

. module Main
. where
.
. main = do
. print $ map fizzbuzz [1..100]
.
. fizzbuzz x | x `mod` 15 == 0 = “FizzBuzz”
. | x `mod` 5 == 0 = “Buzz”
. | x `mod` 3 == 0 = “Fizz”
. | otherwise = show x

60. Cameron Kerr - February 24, 2007

And it still munges the text. Check my blog for what it should look like.

61. Paul - February 24, 2007

It’s a neat little test. I submitted it as a golfing challenge here:

http://golf.shinh.org/p.rb?FizzBuzz

Best solution so far is 50B of Perl. (Unfortunately, solutions are not viewable — or even saved.)

62. Coding Horror - February 27, 2007

Why Can’t Programmers.. Program?

I was incredulous when I read this observation from Reginald Braithwaite: Like me, the author is having trouble with the fact that 199 out of 200 applicants for every programming job cant write code at all. I repeat: they…

63. Syarzhuk - February 27, 2007

QBasic is easier :)

10 DATA “”, “”, “Fizz”, “”, “Buzz”, “Fizz”, “”, “”, “Fizz”, “Buzz”, “”, “Fizz”, “”, “”, “FizzBuzz”
20 DIM A$(15)
30 FOR I = 1 TO 15
40 READ A$(I)
50 NEXT I
60 FOR I = 1 TO 100
70 j = I MOD 15
80 IF A$(j) “” THEN PRINT A$(j) ELSE PRINT I
90 NEXT I

64. Cryptnotic - February 27, 2007

How about this one (just for fun):

int main()
{
int i;
for (i=1; i

65. Cryptnotic - February 27, 2007

Weak. Stupid less than signs.

int main()
{
int i;
for (i=1; i<=100; i++) {
switch(i % 15) {
case 0: printf(“fizzbuzz\n”); break;
case 3:
case 6:
case 9:
case 12: printf(“fizz\n”); break;
case 5:
case 10: printf(“buzz\n”); break;
default: printf(“%d\n”, i);
}
}
}

66. AlxShr - February 27, 2007

PHP::

for ($i=1;$

67. AlxShr - February 27, 2007

for ($i=1;$<101;$i++) {
if ($i%3==0)
echo “fuzz”;
if ($i%5==0)
echo “buzz”;
if ($i%3 && $i%5)
echo $i;
}

68. Patrik - February 27, 2007

.NET console application written in C#:

for (int i = 1; i

69. Patrik - February 27, 2007

Hmm. There might be something wrong with posting comments with the “less than” character. Anyway, here is the .NET console application solution written in C#:

for (int i = 1; i <= 100; i++)
{
Console.WriteLine((i % 3 == 0 && i % 5 == 0) ? “FizzBuzz” : ((i % 3 == 0) ? “Fizz” : (i % 5 == 0) ? “Buzz” : i.ToString()));
}

Joseph - February 28, 2010

hey so how do you get the program to display the numbers?

Keith - January 5, 2011

That’s the i:ToString() part. If you can’t follow the example, you probably need to brush up on ?: syntax.

70. Brent Ashley - February 27, 2007

fizzbuzz.sh:

echo “1\n2\nfizz\n4\nbuzz\nfizz\n7\n8\nfizz\nbuzz\n11\nfizz\n13\n14\nfizzbuzz\n16\n17\nfizz\n19\nbuzz\nfizz\n22\n23\nfizz\nbuzz\n26\nfizz\n28\n29\nfizzbuzz\n31\n32\nfizz\n34\nbuzz\nfizz\n37\n38\nfizz\nbuzz\n41\nfizz\n43\n44\nfizzbuzz\n46\n47\nfizz\n49\nbuzz\nfizz\n52\n53\nfizz\nbuzz\n56\nfizz\n58\n59\nfizzbuzz\n61\n62\nfizz\n64\nbuzz\nfizz\n67\n68\nfizz\nbuzz\n71\nfizz\n73\n74\nfizzbuzz\n76\n77\nfizz\n79\nbuzz\nfizz\n82\n83\nfizz\nbuzz\n86\nfizz\n88\n89\nfizzbuzz\n91\n92\nfizz\n94\nbuzz\nfizz\n97\n98\nfizz\nbuzz\n”

71. lowly programmer - February 27, 2007

int
main(int argc,char *argv[])
{
int ii;

for(ii=0;ii++

72. A.D. - February 27, 2007

In T-SQL:

DECLARE @i int
SET @i = 1
WHILE (@i

73. Michael Letterle - February 27, 2007

I took a slightly different approach then Patrik, but similar:

for(int x=1; x

74. Michael Letterle - February 27, 2007

I took a slightly different approach then Patrik, but similar:

for(int x=1; x <= 100; ++x) { Console.WriteLine((x % 3 == 0 ? “Fizz” : “”) + (x % 5 == 0 ? “Buzz” : “”) + ((x % 3 != 0 && x % 5 != 0) ? x.ToString() : “”) ); }

75. Casual Observer - February 27, 2007

Another observation:

If the code is only three lines long, but is still hard to read, that’s also a bad sign.

If someone else wants to read your code, the simple version is better unless you have a very good reason (such as speed) for using peculiar shortcuts. Developer time is usually more important unless you have found a bottleneck.

Verbose code >> terse code 99% of the time. Some of you are showing off. Sorry, wouldn’t want you to work on my team.

76. matt - February 27, 2007

C’mon, everyone, you’re forgetting the master of all programming languages: Visual Basic for Applications (Excel in this case)! :)

Sub fizzbuzz()
For i = 1 To 100
If i Mod 3 = 0 Then
If i Mod 5 = 0 Then
Range(“A1″).Offset(i – 1, 0).Value = “fizzbuzz”
Else
Range(“A1″).Offset(i – 1, 0).Value = “fizz”
End If
Else
If i Mod 5 = 0 Then
Range(“A1″).Offset(i – 1, 0).Value = “buzz”
Else
Range(“A1″).Offset(i – 1, 0).Value = i
End If
End If
Next i
End Sub

chance - July 2, 2010

VBA would look like this, as the requirements didn’t mention any excel sheets
Sub FizBizz()

For i = 1 To 100
If i Mod 15 = 0 Then
Debug.Print (“Fizz-Buzz”)

ElseIf i Mod 5 = 0 Then
Debug.Print (“Buzz”)
ElseIf i Mod 3 = 0 Then
Debug.Print (“Fizz”)
Else
Debug.Print (i)
End If

Next i

End Sub

77. Scott Hanselman's Computer Zen - February 27, 2007

You Can’t Teach Height – Measuring Programmer Competence via FizzBuzz

78. medbob - February 27, 2007

Took about 3 – 5 minutes because I couldn’t remember if the operator was DIV or MOD….

program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;
var i : Integer;
output : String;
begin
{ TODO -oUser -cConsole Main : Insert code here }
for I := 1 to 100 do
begin
Output := ”;
//Writeln(i,i mod 3);
if (i mod 3 = 0) then
Output := ‘Fizz';
if (i mod 5 = 0) then
if (i mod 3 = 0) then
output := ‘Fizz-Buzz’
else
output := ‘Buzz’
else
if Output = ” then
Output := IntToStr(i);

Writeln(Output);
end;
Read(i);

end.

79. Fratm - February 27, 2007

PERL:
while ($i

80. gorgan - February 27, 2007

You just can’t beat the clean look of perl!

print$_%3?$_%5?$_:’Buzz':$_%5?’Fizz':’FizzBuzz’,”\n”for 1..100;

81. Fratm - February 27, 2007

I used an less than = but couldnt post it.. so changed it a little.

while ($i != 101)
{
if ($i%3==0) { $out= “fizz”; }
if ($i%5==0) { $out .= “buzz”; }
if ($out) {print “$out \n”} else { print “$i\n”; }
++$i;
undef ($out);
}

82. rascunho » Seção de dados do blog » links for 2007-02-27 - February 27, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding « Imran On Tech 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”. (tags: tickletux.wordpress.com 2007 at_tecp Fizz Buzz FizzBuzz programming test) [...]

83. Too Embarrassed - February 27, 2007

VB 6 Immediate window:

for x = 1 To 100: Debug.Print switch(x Mod 3 = 0,”fizz”,x Mod 5 = 0,”buzz”,x Mod 15 = 0,”fizzbuzz”,True,x):next

84. Shabaka - February 27, 2007

These programming tests aren’t real world situations anyway. Every scientist knows that an object behaves differently under observation. Job interviews are already tense situations. Then to have to write code with someone breathing down your neck…I don’t think testing like this is a good way to screen out candidates. For one thing, if you are hiring a web developer, chances are s/he will be working online. What’s wrong with using Google? We’ve gotten to a point where we don’t have to recreate the wheel. What purpose does FizzBuzz serve in the real world? In my CompSci class, the prof said that programmers are lazy. If the problem has already been solved, whats the point so sweating about it?

Kam - December 21, 2010

obaka,
this is a warmup question. anyone should slide into it, and be smiling and less stressed by the end!

85. Tim Balbekov - February 27, 2007

I’m 15 and have never taken a programming class. Seven minutes in C:

#include “stdio.h”

int main() {
int i;
for(i = 1; i

ErnWong - December 8, 2012

I’m 14! JavaScript: ( function FizzBuzz( undefined ) {
for ( var i = 0; i <= 100; i++ ) {
var out = undefined;
if ( i % 3 === 0 ) {
out = "Fizz";
}
if ( i % 5 === 0 ) {
//out = [(out || ""), "Buzz"].join("");
// or request for Fizz-Buzz instead:
out = [(out? out + "-" : ""), "Buzz"].join("");
}
console.log( out || i );
}
} )();

Q. Programming class?

A. Google Search.

86. LowJo - February 27, 2007

Alright smart guys.

How about some OO? ;)

using System;

internal class Program
{
private static void Main()
{
for( int i = 1; i

87. Tim Balbekov - February 27, 2007

#include “stdio.h”

int main() {
int i;
for(i = 1; i LESS_THAN_GETS_FILTERED 100; i++) {
if( (i % 3 == 0) && (i % 5 == 0))
printf(“FizzBuzz\n”);
else if(i % 3 == 0)
printf(“Fizz\n”);
else if(i % 5 == 0)
printf(“Buzz\n”);
else printf(“%i\n”, i);
}

return 1;
}

88. Eric - February 27, 2007

my perl version (59 chars, borrowing some ideas from previous posts):
print+($_%3?””:”Fizz”).($_%5?””:”Buzz”)||$_,”\n”for 1..100;

89. Andy LeClair - February 27, 2007

Freshman at Northeastern University. 5 minutes in Pretty Big Scheme (PLT’s MzScheme (which includes R5RS) and the HTDP.org teaching languages)

;; fizzbizz: Number -> String
;; prints out the numbers from 0 to [sub1 n], fizz on a mult. of 3,
;; bizz on 5, and fizzbizz on both
(define (fizzbizz n)
(build-list n (lambda (x)
(cond
[(and (= 0 (modulo x 3))
(= 0 (modulo x 5))) "fizzbizz"]
[(= (modulo x 3) 0) "fizz"]
[(= (modulo x 5) 0) "bizz"]
[else x]))))

90. Andy LeClair - February 27, 2007

follow that up with:

(fizzbizz 100) or up to whatever you please.

91. otli4nitsa and keda - February 27, 2007

in perl… 67b :) paul, how’d you do 50b? plz post the code.

for(1..100){print ” “,$_%3?$_%5?$_:’fizz':$_%5?’buzz':’fizzbuzz';}

92. Ayende @ Rahien - February 27, 2007

If Program I Can’t, Programmer Am I?

If Program I Can’t, Programmer Am I?

93. Steve - February 27, 2007

>To Shabaka:
>These programming tests aren’t real world situations anyway.

You’re right. These programming tests are far simpler than real world situations. If you can’t hack a simple contrived problem like FizzBuzz, it’s very likely you can solve a real world problem.

94. Dan - February 27, 2007

Javascript…

function FizzBuzz()
{
var strAlert=””;
for(var i=1; i

95. Dan - February 27, 2007

Javascript:
(I cant believe they don’t escape your input…)

function FizzBuzz()
{
var strAlert="";
for(var i=1; i<=100; i++)
{
strAlert += (i%3==0)?"Fizz":"";
strAlert += (i%5==0)?"Buzz":"";
strAlert += (i%3!=0 && i%5!=0)?i:"";
strAlert += ", "
}
alert(strAlert.substring(0, strAlert.length-2));
}

96. JimGee - February 27, 2007

I would happy if they can do this.

/* Comments about program go here*/
#include “stdio.h”
int main(int argc, char* argv[])
{
int i;
for(i=1; i

97. Don Beal - February 27, 2007

What a great post…

I have been writing code for about 20 years now, it’s amazing how in the past 10 nobody wants anything but VB for in-house stuff (mostly for TTM reasons) but this is a tremendous example of how there are a million ways to accomplish the same thing in 100 different languages.

I recently went out to dinner with a fellow consultant and we had this discussion about how new programmers know the latest .NET and nothing else and it is just pitiful how they have no foundation whatsoever. If it weren’t for Randy Birch I doubt they would ever pass a mid-term. I think that is the byproduct of making languages easier to read/write.

A lot of people can paint a house, but I wouldn’t call them all house painters.

Again, awesome thread.

98. JimGee - February 27, 2007

‘/* Comments about program go here*/
#include “stdafx.h”
int main(int argc, char* argv[])
{
int i;
for(i=1; i

99. JimGee - February 27, 2007

I would happy if they can do this.

/* Comments about program go here*/
#include “stdafx.h”
int main(int argc, char* argv[])
{
int i;
for(i=1; i&lt 101; i++)
{
printf(“%d “,i);
if(i % 3 ==0)
printf(“Fizz”);
if(i % 5 == 0)
printf(“Buzz”);
printf(“\n”);
}
return 0;
}

100. VOID - February 27, 2007

def FizzBuzz():
for i in range(1,101):
n=i%15
if(n==0): print “FizzBuzz”
elif(n in [3,6,9,12]):print “Fizz”
elif(n in [5,10]):print “Buzz”
else: print i

FizzBuzz()

Had to be original.

vurp - May 2, 2011

out={(False, False):0, (True, False):’Fizz’, (False, True):’Buzz’, (True, True):’FizzBuzz’}
for i in range(1, 101):
out[(False, False)]=i
print out[(not i%3, not i%5)]

101. dumb - February 27, 2007

/

102. rob - February 27, 2007

the real test should be to leave a coding example and have the < and > show up ;)

103. imdumb - February 27, 2007

help me I’m dumb
/

104. Pat - February 27, 2007

I’ve done FizzBuzz in C language in 7 minutes and swap variables in 20 seconds. I think this is not bad and also not impressive. But these questions are too much hazardous. Too much synthetic to bring some guy down at the interview. Personally I’ve been two times a victim of that smart questions that I have not passed. However I consider myself as above average skilled programmer.

105. Steve - February 27, 2007

To Pat:
>Personally I’ve been two times a victim of that smart questions
>that I have not passed. However I consider myself as above
>average skilled programmer.

How do you know you’re an above average skilled programmer? There literally billions of dumb people roaming this earth who are deluded they are very intelligent though reality tells a different story. What makes you think you’re immune to being deluded about your own skills and intelligence?

Ask yourself this: Why did it take you 7 minutes to write FizzBizz? Do you type really slow? Did you have to fix bugs? Did you have to fix compiler errors? Did you know right away to use the mod operator?

Don’t you think if a person has trouble with a problem like this, they might do a poor job at solving real world problems with which the complexity of the problems are orders of magnitude more complicated?

106. robby - February 27, 2007

LoL its funny cause all these guys are like bragging that they can code this program by putting the code in their comment..

BUT ITS ALL WRONG

if i = 15 it would print, FIZZBUZZ
FIZZ
BUZZ
resulting it occurring twice..
cause you have no ‘continue’ after your if statement that checks for 3 and 5

it would also make more sense to check if it is divisible by 15 rather than 3 && 5

Hopeless.. im telling your boss to outsource your job to India.

107. Ray - February 27, 2007

in IL:

.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 120 (0x78)
.maxstack 2
.locals init ([0] int32 i,
[1] string ‘value’,
[2] bool CS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0065
IL_0005: nop
IL_0006: ldloca.s i
IL_0008: call instance string [mscorlib]System.Int32::ToString()
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: ldc.i4.3
IL_0010: rem
IL_0011: brtrue.s IL_001e
IL_0013: ldloc.0
IL_0014: ldc.i4.5
IL_0015: rem
IL_0016: ldc.i4.0
IL_0017: ceq
IL_0019: ldc.i4.0
IL_001a: ceq
IL_001c: br.s IL_001f
IL_001e: ldc.i4.1
IL_001f: stloc.2
IL_0020: ldloc.2
IL_0021: brtrue.s IL_002d
IL_0023: nop
IL_0024: ldstr “FizzBuzz”
IL_0029: stloc.1
IL_002a: nop
IL_002b: br.s IL_0059
IL_002d: ldloc.0
IL_002e: ldc.i4.3
IL_002f: rem
IL_0030: ldc.i4.0
IL_0031: ceq
IL_0033: ldc.i4.0
IL_0034: ceq
IL_0036: stloc.2
IL_0037: ldloc.2
IL_0038: brtrue.s IL_0044
IL_003a: nop
IL_003b: ldstr “Fizz”
IL_0040: stloc.1
IL_0041: nop
IL_0042: br.s IL_0059
IL_0044: ldloc.0
IL_0045: ldc.i4.5
IL_0046: rem
IL_0047: ldc.i4.0
IL_0048: ceq
IL_004a: ldc.i4.0
IL_004b: ceq
IL_004d: stloc.2
IL_004e: ldloc.2
IL_004f: brtrue.s IL_0059
IL_0051: nop
IL_0052: ldstr “Buzz”
IL_0057: stloc.1
IL_0058: nop
IL_0059: ldloc.1
IL_005a: call void [mscorlib]System.Console::WriteLine(string)
IL_005f: nop
IL_0060: nop
IL_0061: ldloc.0
IL_0062: ldc.i4.1
IL_0063: add
IL_0064: stloc.0
IL_0065: ldloc.0
IL_0066: ldc.i4.s 100
IL_0068: cgt
IL_006a: ldc.i4.0
IL_006b: ceq
IL_006d: stloc.2
IL_006e: ldloc.2
IL_006f: brtrue.s IL_0005
IL_0071: call string [mscorlib]System.Console::ReadLine()
IL_0076: pop
IL_0077: ret
} // end of method Program::Main

108. Daruku - February 27, 2007

// c#

class FizzBuzz
{
static void Main(string[] args)
{
for (int i = 1; i

109. C Is A Write-Only Language - February 27, 2007

You suckas. In APL I can solve either problem in one character: a

I’ll take my job offer now, thanks.

110. DeathToSpam - February 27, 2007

ASP/VBScript, complete with purdy output formatting:

” & vbNewLine
Next %>

111. DeathToSpam - February 27, 2007

ASP/VBScript, complete with purdy output formatting:

Dim iLoop, bIsMultipleOfThree, bIsMultipleOfFive, sOutput

For i = 1 to 100
bIsMultipleOfThree = (i MOD 3 = 0)
bIsMultipleOfFive = (i MOD 5 = 0)

If (i ” & vbNewLine
Next

112. DeathToSpam - February 27, 2007

Tried to post, but characters got all truncated after submitting. :( Oh well.

113. Lumpio- - February 27, 2007

I can’t believe nobody thought of

for i in range(1, 101): print [i, "Fizz", "Buzz", "FizzBuzz"][int(i % 3 == 0) + int(i % 5 == 0) * 2]

114. Leonardo Herrera - February 28, 2007

Bah, couldn’t beat the 49 bytes mark (mine is 54 bytes).
print$_%3?$_%5?$_:””:Fizz,$_%5?””:Buzz,”\n”for 1..100;

115. Leonardo Herrera - February 28, 2007

(And I keep marveled at our capacity to intentionally miss the point.)

116. Marek Pułczyński - February 28, 2007

Just for completness – BASH oneliner (dumbly assuming modulo is as expensive as comparison)

for x in `seq 100` ; do if [ `expr $x % 15` -eq 0 ] ; then echo FizzBuzz; elif [ `expr $x % 3` -eq 0 ]; then echo Fizz; elif [ `expr $x % 5` -eq 0 ]; then echo Buzz; else echo $x; fi; done

117. Jason - February 28, 2007

A little more convoluted than the examples above in Python, but still (fairly) followable:

print ‘\n’.join([{(False, False): y[-1], (True, False): “Fizz”, (False, True): “Buzz”, (True, True): “FizzBuzz”}[y[0]] for y in [((x%3==0, x%5==0), str(x)) for x in range(1, 101)]])

118. mobmash blog » Blog Archive » links for 2007-02-28 - February 28, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding « Imran On Tech (tags: programming interview) [...]

119. bumSki - February 28, 2007

// in C++
int main()
{
for (int count = 1; count

120. Matt - February 28, 2007

This is the shortest way I could think of doing it in C++. Of course, the layout is absolutely horrid (no whitespace, etc) but it’s short and it works:

#include
int main()
{
for(int i=1;i

121. MrMajestyk - February 28, 2007

For i As Integer = 1 To 100
If i Mod 3 = 0 Then
lblSolution.Text &= “Fizz” & vbCrLf
ElseIf i Mod 5 = 0 Then
lblSolution.Text &= “Buzz” & vbCrLf
ElseIf i Mod 3 = 0 And i Mod 5 = 0 Then
lblSolution.Text &= “FizzBuzz” & vbCrLf
Else
lblSolution.Text &= i & vbCrLf
End If

Next

122. Thomas Moitie - February 28, 2007

“Want to know something scary ? – the majority of comp sci graduates can’t.”

I’m 17, self-taught at php. A language in which I came up with a solution within 1 minute. I am utterly astounded if this statement is true

Kam - December 21, 2010

key words: self-taught.
If I asked you something you didn’t know, you’d LEARN IT.

123. someone tired of writing code but loving of doing it also - February 28, 2007

after 15 years of c++ experience.
i wonder why you check three conditions for FizzBuzz thing!
one for fizz, one for buzz, and another for fizzbuzz..
wouldnt it be reasonable to use a boolean to control not to write the number. but only checking if it is a modul of 5 or 3. and after the each loop, feeding the line.

one thing is favorable, you should write a code to be extended easily in the future.

124. Thomas Messier - February 28, 2007

One test we used to administer for web developers was ask them to code a simple calendar. We gave them plenty of time, along with all the reference manuals. Lots of people couldn’t do it in 30 minutes.

125. Carl - February 28, 2007

What? No one’s tried to use C++ templates to compute FIZBUZ at compile time instead of at runtime.

126. Syed Muhammad - February 28, 2007

programming requires a little bit of talent and some passion of PROBLEM SOLVING. probably that’s why they can’t write the code. no problem solving skills.

127. Procyon - February 28, 2007

windows batch file:

@echo off
set count=1
:loop
set div3=%count%
set div5=%count%
:loop3
set /a div3 -= 3
if not %div3% leq 0 goto :loop3
:loop5
set /a div5 -= 5
if not %div5% leq 0 goto :loop5
if %div3%==0 (
if %div5%==0 (
echo fizzbuzz
) else (
echo fizz
)
) else (
if %div5%==0 (
echo buzz
) else (
echo %count%
)
)
set /a count += 1
if %count% lss 100 goto :loop

128. Unmaintainable Code - February 28, 2007

#include
int main(){int i;for(i=1;101>i;++i)printf(i%15?i%3?i%5?”%d\n”:
“Buzz\n”:”Fizz\n”:”FizzBuzz\n”,i);}

129. Anonymous - February 28, 2007

main(i){for(i=0;i

130. Matt - February 28, 2007

Here’s the main part of my code since my post was clipped for some reason:

std::cout

131. GS - February 28, 2007

Since everyone else is posting their solution:

#FIZZBUZZ.PY
for i in range(1,101):
flag = True
num = []
if i % 3 == 0:
num.append(“Fizz”)
flag = False
if i % 5 == 0:
num.append(“Buzz”)
flag = False
num = ”.join(num)
if flag:
num = str(i)
print “%s\n” % (num),

132. Trey Marcus - February 28, 2007

I’m not at all surprised at this because the interviewer is apparently asking a person to use a piece of paper or whiteboard to write a computer program. This is a completely foreign environment for most programmers I know and under the stress of an interview I am not at all surprised that most programmers would have trouble with such a task.

If you want to know if a person can architect a solution to a FizzBuzz style problem then I think its fine to ask them how they might go about solving it. Asking someone to write a computer program on a piece of paper seems a bit assinine and I think such interview tactics say far more about the interviewer than the interviewee.

If you want to test a person’s programming abilities… great. Give him a computer and a problem and leave him to work as he normally would to find a problem even if its just a few minutes.

Kam - December 21, 2010

Doesn’t anyone learn to code without the compiler anymore? Egads! Part of my debugging regimen is to READ THE CODE. I catch more bugs that way…

[and the point isn't to get the syntax right, but to show problem solving ability.]

Trey Marcus - March 3, 2011

A friend googled me, found this page, and asked me about my comment, which led me here. It is in fact my name, yet I have no recollection of ever writing this comment, so I thought I would comment on the comment that I may or may not have written:

I interviewed for a position in 2000 when I knew Java much better than C++, and I was asked to solve a problem on a Writeboard in C++. I did it, but was unsure of the syntax to use in C++ for an abstract function- so I wrote [abstract] and said whatever that’s called in C++. (It’s “virtual”.) I got the job, and was asked a few months later to interview two other people the same way on the writeboard. Neither of them, both of whom were C++ OOP “experts” according to their resumes, could even start writing basic code, let alone get far enough to write a virtual function. So I disagree with “Trey Marcus”: There certainly is a time and a place for paper and writeboard coding tests, if the test is conceptual based and simple enough.

133. Bob On Development » The Crisis of Programmer Competence - February 28, 2007

[...] In fact some interviewers have taken to screening all applicants early with some trivial programming problem like the FizzBuzz Question. [...]

134. shoebappa - February 28, 2007

Jacob, I’d seen the opposite question, to swap two variables without using a third…

$x = 5;
$y = 11;

$x = $x + $y; // 5+11 = 16
$y = $x – $y; // 16-11 = 5
$x = $x – $y; // 16-5 = 11

guess it only works with numbers, but using a third variable is the obvious solution, it’s unfortunate that you could weed anyone out with that question…

135. Jason - February 28, 2007

Common Lisp, format-style:
(loop for i from 1 to 100
do (format t “~A ~:[~;Fizz~]~:[~;Buzz~]~%” i (zerop (mod i 3)) (zerop mod i 5))))

Pascal Bourguignon - September 17, 2012

Doesn’t answer the specs.
Try:

(loop for n from 1 to 100 do (format t “~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%” (mod n 3) (mod n 5) n))

136. test - February 28, 2007
137. test - February 28, 2007

< >

138. Exec - February 28, 2007

XSL version
=======

<?xml version=”1.0″ encoding=”UTF-8″?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” xmlns:fo=”http://www.w3.org/1999/XSL/Format”>

<xsl:template match=”/”>
<xsl:call-template name=”fizzLogic”>
<xsl:with-param name=”iCount” select=”‘1′”/>
</xsl:call-template>
</xsl:template>

<xsl:template name=”fizzLogic”>
<xsl:param name=”iCount”/>

<xsl:if test=”$iCount &lt; 101″>
<xsl:choose>
<xsl:when test=”$iCount mod 3=0 and $iCount mod 5 = 0″>FizzBuzz</xsl:when>
<xsl:when test=”$iCount mod 3=0″>Fizz</xsl:when>
<xsl:when test=”$iCount mod 5=0″>Buzz</xsl:when>
<xsl:otherwise><xsl:value-of select=”$iCount”/></xsl:otherwise>
</xsl:choose>

<xsl:call-template name=”fizzLogic”>
<xsl:with-param name=”iCount” select=”$iCount+1″/>
</xsl:call-template>

</xsl:if>
</xsl:template>

</xsl:stylesheet>

139. The Mu » Blog Archive » Programmers that can’t program - February 28, 2007

[...] an aside, I gave the FizzBuzz problem a shot too.  I included my result below (it took me almost twenty minutes because I [...]

140. Sougent - February 28, 2007

I’m waiting for the solution in COBOL…….

141. Vincent McNabb - February 28, 2007

In JavaScript:

for(i = 1; i < 101; i++) {
  if(i%3==0) document.write("Fizz");
  if(i%5==0) document.write("Buzz");
  if(!((i%3==0)|(i%5==0))) document.write(i);
  document.write("<br>");
}

Basic

for i = 1 to 100
  if i mod 3 = 0 then print "Fizz"
  if i mod 5 = 0 then print "Buzz"
  if i mod 3 > 0 and i mod 5 > 0 then print str$(i)
next

142. Thomas Chapin - February 28, 2007

I wonder if you replace the lesser than symbol with the html escaped version, it will work? Testing now: <

143. Thomas Chapin - February 28, 2007

Ok. Cool. It looks like that worked.

Here’s my version done in javascript:

<script>

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

   if(i%15==0){
      document.write(“FizzBuzz<BR>”);
   }else if(i%5==0){
      document.write(“Buzz<BR>”);
   //
   }else if(i%3==0){
      document.write(“Fizz<BR>”);
   }else{
      document.write(i+”<BR>”);
   }

}

</script>

144. Thomas Chapin - February 28, 2007

whoops I left two slashes in there on accident (I was going to put comments in there but decided to remove them)

145. Ian - February 28, 2007

“I’m waiting for the solution in COBOL…”

something like (I don’t have a compiler to hand and it’s been a while):

PERFORM VARYING Count FROM 0 BY 1 UNTIL Count > 99
COMPUTE Three-Mod = FUNCTION MOD (Count, 3).
COMPUTE Five-Mod = FUNCTION MOD (Count, 5).
IF Three-Mod = 0 AND Five-Mod = 0 THEN
DISPLAY “FizzBuzz”
ELSE
IF Three-Mod = 0 THEN
DISPLAY “Fizz”
ELSE
IF Five-Mod = 0 THEN
DISPLAY “Buzz”
ELSE
DISPLAY Count
END-IF
END-IF
END-PERFORM

But as the nested IF’s suck, with an EVALUATE something like this:

PERFORM VARYING Count FROM 0 BY 1 UNTIL Count > 99
COMPUTE Three-Mod = FUNCTION MOD (Count, 3).
COMPUTE Five-Mod = FUNCTION MOD (Count, 5).
EVALUATE Three-Mod ALSO Five-Mod
WHEN 0 ALSO 0 DISPLAY “FizzBuzz”
WHEN 0 ALSO >0 DISPLAY “Fizz”
WHEN >0 ALSO 0 DISPLAY “Buzz”
WHEN >0 ALSO >0 DISPLAY Count
END-EVALUATE
END-PERFORM

146. flickrhoneys - February 28, 2007

Grok coding is one of my many hobbys, but i need someone to explain it to me :(

147. Fahd Mirza - February 28, 2007

Reading this thread was a splendid education

148. eric - February 28, 2007

indeed scary

that FizzBuzz problem should take 1-2 minutes max for an experienced developer.

Any more directly presents hesitance and a lack of skill. Unable for someone to answer it should mean that they chose a wrong path and should never have become developers.

149. eric - February 28, 2007

I cannot help noticing how simple this program is, and how many people have posted their solutions here, (trying of course to give a quick and clever minimalistic solution)

I haven’t read all the replies above me, and I am not surprised to found at least 3 solutions which do not work.

Not to name any but some solutions above print “Fizz Buzz FizzBuzz” when they find multiples of 3 and 5.

Being quick and rushing are not the same thing.

150. Alex - February 28, 2007

Can’t forget C# with a little LINQ…

foreach (string s in Sequence.Range(1,100).Select<int,object>(i => ((i%15)==0) ? “FizzBuzz” : ((i%3)==0) ? “Fizz” : ((i%5)==0) ? “Buzz” : i.ToString())) Console.WriteLine(s);

151. Ross Hawkins - February 28, 2007

IBM Lotus Notes @Function FizzBuzz

@For(n := 1; n <= 100; n := n + 1; output := output + @If(@Modulo( n ; 3 ) = 0 & @Modulo( n ; 5 ) = 0; “FizzBuzz”;@Modulo( n ; 3 ) = 0; “Fizz”; @Modulo( n ; 5 ) = 0; “Buzz” ; @Text(n) ));output;

or

@For(n := 1; n <= 100; n := n + 1;tmp := @If(@Modulo( n ; 3 ) = 0; “Fizz”; “”);tmp := tmp + @If(@Modulo( n ; 5 ) = 0; “Buzz”; “”);output := output + @If(@Length(tmp) =0; @Text(n); tmp ));output

Add a @Newline in there for readability if you wish. The great thing about the IBM/Lotus solution is that there’s hardly anyone out there who’s going to bother to test it.

152. Yuri - February 28, 2007

Someone wrote:

def FizzBuzz():
for i in range(1,101):
n=i%15
if(n==0): print “FizzBuzz”
elif(n in [3,6,9,12]):print “Fizz”
elif(n in [5,10]):print “Buzz”
else: print i

FizzBuzz()

Had to be original.

Hehe, nice!

153. Reality Me » And they call themselves programmers… - February 28, 2007

[...] he made a very good post asking "Why can’t programmers.. Program?" He referenced Imran on Tech who uses a simple problem to figure out if his prospective candidates can code. Imran also has good [...]

154. News Flash: Tech Interviews Don’t Work at mark++ - February 28, 2007

[...] Imram [...]

155. The Mu » Blog Archive » Blogosphere abuzz over FizzBuzz - February 28, 2007

[...] of traffic was created by Imran’s original post, Reg Braithwaite’s comment, and Jeff Atwood’s followup. All over the blogosphere, eager [...]

156. silentflute » Programmers can’t program? - February 28, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding [...]

157. slimCODE, aka Martin Plante : Comment reconnaître un bon développeur - February 28, 2007

[...] à un poste de développeur est recommencé depuis un billet de Imran qui se sent obligé de mettre la barre très basse lors d’entrevues. Il propose l’implémentation d’un jeu d’enfant appelé FizzBuzz (tout bon [...]

158. Dilbert - February 28, 2007

There is some major flaws in this testing approach with any corporate programmer. First of all, you didn’t give him any time to discuss the requirements with analysts and end users, nor did you present him with use cases, workflows, or activity diagrams. You didn’t bother to explain unit test plans or QA bug tracking, nor did you even have the courtesy of scheduling five meetings to review specs, user interfaces, budgets, or schedules! You are also going to need to provide 45 minutes of time for the programmer to check his daily e-mail from his 5 supervisors who want to know what he is doing. AND YOU WONDER WHY THEY FAIL THE TEST???!!!

159. anon - March 1, 2007

Didn’t know about the MOD operator, so had to try a different method:

Sub FizzBuzz()

t3 = 0
t5 = 0

For i = 1 To 100

t3 = t3 + 1
t5 = t5 + 1
Number = False

If t3 = 3 And t5 5 Then
Cells(i, 5) = “Fizz”
t3 = 0
Number = True
End If

If t5 = 5 And t3 3 Then
Cells(i, 5) = “Buzz”
t5 = 0
Number = True
End If

If t3 = 3 And t5 = 5 Then
t3 = 0
t5 = 0
Cells(i, 5) = “FizzBuzz”
Number = True
End If

If Number = False Then
Cells(i, 5).Value = i
End If
Next

End Sub

160. Nick - March 1, 2007

In Prolog…

start :- fizz_buzz(1,100).

fizz_buzz(Lo,Hi) :-
Lo <= Hi ,
output(Lo) ,
Next is Lo+1 ,
FizzBuzz(Next,Hi).
FizzBuzz.

output( N ) :-
R3 is N mod 3 ,
R5 is N mod 5 ,
text( R3 , R5 , N , T ) ,
write(T) ,
nl.

text( 0 , 0 , N , N ).
text( _ , 0 , _ , ‘Fizz’ ).
text( 0 , _ , _ , ‘Buzz’ ).
text( _ , _ , _ , ‘FizzBuzz’ ).

161. The FizzBuzz Fizz And Weak Programmers on iface thoughts - March 1, 2007

[...] rightly points out that a lot of programmers, who talk well about programming, cannot actually code. Jeff Atwood follows up with his views on it. My experience has been a little different, when I got [...]

162. Solving FizzBuzz Problem | FuCoder.com - March 1, 2007

[...] quoted Irman’s FizzBuzz question, a trivial programming problem but surprisingly has stumbled many job applicants. Here is the [...]

163. Pete - March 1, 2007

I’m not really much of a programmer, but here’s my Fizzbuzz in C++:

#include
using namespace std;

int main(){
int x=0;
do {
x++;
cout

164. Pete - March 1, 2007

^that broke….

#include
using namespace std;

int main(){
int x=0;
do {
x++;
cout

165. Pete - March 1, 2007

……

166. Scorpyosis - March 1, 2007

You will never hire me, in spite of I can swap two variables (a,b)without creating a third variable :
a = a + b
b = a – b
a = a – b

>>> In respond to this comment :
3. Jacob – January 24, 2007
Want another good filter? This surprised me, but turns out to be a good indication of whether someone has actually ever programmed before.

Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.

If they don’t *start* with creating a third variable, you can pretty much write that person off. I’ve found that I can cut a third to half my (admittedly at that point unscreened) applicants with that question alone.

167. Don - March 1, 2007

“Dilbert (Feb 28)”, funny point, don’t forget to mention the one guy that is neither engineer nor developer somehow getting involved and insisting on changing the scope of the project every third minute.

;-?

168. A ver si no sabemos programar… « Para bellum - March 1, 2007

[...] autor al que se refiere es Imran, que está rechazando a montañas de programadores que no saben escribir un simple programa. Después de unas cuantas pruebas y errores descubrí que a las personas que se pelean con el [...]

169. Mike Nolan - March 1, 2007

81 characters in PHP but I’m sure it can be reduced a little:

for($i=1;$i

170. Dave - March 1, 2007

– in oracle plsql
begin
dbms_output.enable;
for i in 1..100
loop
if mod(i,3)=0
then dbms_output.put_line(‘Fizz’);
elsif mod(i,5) =0
then dbms_output.put_line(‘Bizz’);
elsif mod(i,3)=0 and mod(i,5)=0
then dbms_output.put_line(‘FizzBizz’);
else
dbms_output.put_line(i);
end if;
end loop;
end;

171. Dave - March 1, 2007

– correction…plsql
begin
dbms_output.enable;
for i in 1..100
loop
if mod(i,3)=0 and mod(i,5)=0
then dbms_output.put_line(‘FizzBizz’);
elsif mod(i,3)=0
then dbms_output.put_line(‘Fizz’);
elsif mod(i,5) =0
then dbms_output.put_line(‘Bizz’);
else
dbms_output.put_line(i);
end if;
end loop;
end;

172. Kisara - March 1, 2007

The sad part about this is that it took me about 3 minutes to write.

And I’m 12.

173. C.F. - March 2, 2007

What about this?

public class FizzBuzz {

static final int MAX_NUM = 100;

public static void main(String[] args) {

String str;

for(int i = 1; i

174. steve - March 2, 2007

My first python program. I have been wanting to learn Python so I thought I would install it and try FizzBuzz on for size. I see some other Python examples but this one is a little different. How bad is it?

for x in range(1, 101): # needs to be 101 to include 100 in the loop
out = “” # set reset output
if x%3 == 0: # x evenly divisible by 3
out = ‘Fizz’ # yes
if x%5 == 0: # x evenly divisible by 5
out = out + ‘Buzz’ # yes
if out == “”: # is out null
print x # yes print x
else:
print out # no print out

175. Brian Adkins - March 2, 2007

68 bytes in Ruby

1.upto(100){|i|puts”FizzBuzz#{i}”[i%3==0?0:i%5==0?4:8,i%15==0?8:4]}

176. Scott Hanselman's Computer Zen - Hanselminutes Podcast 53 - Hiring and Interviewing Engineers - March 2, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding (mgx) Don’t Overthink FizzBuzz (mh0) On Interviewing Programmers (mh3) Why Can’t Programmers.. Program? (mgy) Programming Jokes compiled by Raganwald (mh1) The Guerrilla Guide to Interviewing (version 3.0) (mh4) You Can’t Teach Height – Measuring Programmer Competence via FizzBuzz (mgz) What Great .NET Developers Ought To Know (More .NET Interview Questions) (mh2) [...]

177. Brian Adkins - March 2, 2007

Oh man, shaved off 3 bytes :)

1.upto(100){|i|puts”FizzBuzz#{i}”[i%3

178. Brian Adkins - March 2, 2007

1.upto(100){|i|puts”FizzBuzz#{i}”[i%3<1?0:i%5<1?4:8,i%15<1?8:4]}

179. James - March 2, 2007

Response.Write(“1″)
Response.Write(vbcrlf)
Response.Write(“2″)
Response.Write(vbcrlf)
Response.Write(“Fizz”)
Response.Write(vbcrlf)
Response.Write(“4″)
Response.Write(vbcrlf)
Response.Write(“Buzz”)
Response.Write(vbcrlf)
Response.Write(“Fizz”)
Response.Write(vbcrlf)
Response.Write(“7″)
Response.Write(vbcrlf)
Response.Write(“8″)
Response.Write(vbcrlf)
Response.Write(“Fizz”)
etc.

180. Spacecadet - March 2, 2007

Having read almost every comment on this story I’d probably sack the lot of you.
Where’s the input parameters?
Where’s the modularity?
What happens if in 6 months time the requirements change to 4 and 7 being the fizzbuzz numbers?
What happens when the program needs to be used by the french team who need le fizz le buzz?
What happens when the program is up-scaled to cover 0-1000

manman man - September 3, 2010

This would be over-engineering a solution to an obvious interview test question, and missing the point. I wouldn’t be impressed if I saw your OTT answer…

181. Marillionfan - March 2, 2007

And I wouldnt hire any of you in the first place.

Wasting my companies time on a technical pissing contest.

You’re Fired.

182. Brian Adkins - March 2, 2007

Ok, down to 64 bytes in Ruby, but I think I’ve reached an impasse :(

1.upto(?d){|i|puts”FizzBuzz#{i}”[i%3<1?0:i%5<1?4:8,i%15<1?8:4]}

183. Bruce - March 2, 2007

you guys are such nerds. perhaps this sort of question makes sense for grad, but to be honest, it’s useless. show me the data on “passing silly programming questions to good engineers”. Sure they need to understand software, but this sort of micro-rubbish is somewhat irrelevant, certainly in terms of the people I’d hire.

184. Jake Cohen - March 2, 2007

@SpaceCadet,

You forgot to ask if it’s Y10K compliant, in how many languages its documentation is available, and whether it supports TWAIN-compliant scanners.

185. murty - March 2, 2007

I think these are all good observations but we need to keep in mind that we may encounter a programmer who is smarter than us.

Take for example, Jacob’s test – swap the value of 2 variables. He expects the programmer to start with a 3rd variable but one can achieve the desired result without a 3rd variable.

a = 11;
b= 12;

a = a XOR b; //a = 7
b = a XOR b; // b = 11
a = a XOR b; // a = 12

Besides, software engineering is much more than programming. And you all know that.

186. Mark Miller - March 3, 2007

I’ve been surprised in the past at what I hear people who interview for programing positions can’t do. I found this through Giles Bowkett’s blog, and he’s right. If you can’t solve FizzBuzz in a few seconds in your head, you’re not that great. In fact, if memory serves me I think I solved a programming problem like this when I was in high school 20 years ago. To heck with a CS degree. This is elementary stuff.

It is possible for programmers to overthink themselves into a hole, when in fact the problem is very simple. I’ve done it in the past. The few times I did it in an interview was when I was young and naive, and I was trying to impress the interviewer… So that could explain some of the times when it took 15 minutes for someone. Still, do you want to hire someone who overthinks problems?

Try this one on for size. When I got out of college with a CS degree I interviewed at a small company. They asked me this question:

Write a C program that takes an integer and converts it to a string, without using printf(), or any printf() variant. I might’ve been able to use printf() to output the result string. puts() works too. The integer had at least 2 or 3 digits in it, and was pre-assigned to an int variable. I had the solution coded and running in about 5 minutes. They told me that several people they interviewed could not solve it at all.

If anyone wants to try it in other languages, be my guest. The key to the problem is to not use library functions to solve it, only operators native to the language.

I’ve had problems posed to me at interviews that were harder than this, which stumped me, using higher math, or I just didn’t understand the question.

187. Mark Miller - March 3, 2007

Referring to the C problem I posed:

No fair using itoa() either!

188. spacecadet - March 3, 2007

@Jake Cohen
I detected a hint of sarcasm in your reply.

The point I’m trying to make is, I don’t care if it take a programmer 5 minutes or an hour to come up with the solution. What I want to know is, will the programmer apply some professionalism to the problem. Will he take into account changing requirements, will he make sure that basic changes can be made without the need for someone to go digging through code.
Its one thing being some geek hacker, its something else completely to be a professional about your job and to try and engineer your solution in a manner that is fit for the task which the problem solver may not have even seen coming. As a professional YOU are supposed to be experienced, YOU should be able to see how your solution may be needed for many other similar queries. YOU should be able to see past the obvious question asked.
As far as I’m concerned, the geek hackers have their use, but, if comparing building an apartment block to building software, everyone who has posted here has very good experience of laying bricks but no appreciation of how the building needs to be actually used by real people.

189. Shawn - March 3, 2007

Just for nostalgia:

10 i=1
20 IF i 0 THEN
100 PRINT i;
110 ENDIF
120 PRINT
130 i = i + 1
140 GOTO 20
150 ENDIF
160 END

190. Shawn - March 3, 2007

It didn’t automatically filter the text, so I’ll try one more time with escape characters:

10 i=1
20 IF i < 101 THEN
30 IF i MOD 3 < 1 THEN
40 PRINT “Fizz”;
50 ENDIF
60 IF i MOD 5 < 1 THEN
70 PRINT “Buzz”;
80 ENDIF
90 IF i MOD 15 > 0 THEN
100 PRINT i;
110 ENDIF
120 PRINT
130 i = i + 1
140 GOTO 20
150 ENDIF
160 END

191. Shawn - March 3, 2007

Also, for fun:

Interviewee: I know how to programm in FB, do mind if I use that?
Interviewer: Go ahead.

start=1
end=100
fizz=3
buzz=5

192. Sam - March 3, 2007

Forth is under represented. So I’m going to post another Forth example that is even smaller than the first posting.

: eitherFizzBuzz dup 15 mod 0= if .” fizzbuzz” rdrop then ;
: orFizz dup 3 mod 0= if .” fizz” rdrop then ;
: orBuzz dup 5 mod 0= if .” buzz” rdrop then ;
: orNot dup . ;
: result eitherFizzBuzz orFizz orBuzz orNot ;
: fizzbuzz 1 begin dup 16 < while dup result cr 1+ repeat drop ;

193. Sam - March 3, 2007

let’s try coping the right version into the box this time. :(

: fizzbuzz 1 begin dup 101 %lt; while dup result cr 1+ repeat drop ;

194. pef - March 4, 2007

XSLT2:

195. pef - March 4, 2007

<xsl:for-each select=”1 to 100″>
<br/><xsl:value-of select=”if (not(. mod 15)) then ‘FizzBuzz’ else if (not(. mod 5)) then ‘Buzz’ else if (not(. mod 3)) then ‘Fizz’ else .”/>
</xsl:for-each>

196. OJ’s rants » Blog Archive » Why Can’t Programmers Program? - March 4, 2007

[...] come from, and how they get here, it’s no wonder that I have such an opinion. Have a read of this article to see the kinds of problems that computer science students are unable to solve. From the [...]

197. Ken - March 4, 2007

I was able to golf the ruby down by 3 characters :)

1.upto(?d){|i|p"#{[i%3<1?:Fizz:n='',i%5<1?:Buzz:n&&=i]}"}

198. Ken - March 4, 2007

Oops that’s 6 characters shorter using p, which is cheating a bit (quotes in output and all that). It’s 3 shorter if I had pasted the right one, using puts.

199. JJ - March 4, 2007

The reason why people can’t even program is, they are not even given a chance. You finish school and no one wants to hire you. 2 years pass and then employers expect you to program, when was the last time you did that?

I think people should be hired because they have merit, ambition, hard workers, eager to learn etc… Because you can hire computer geeks, only to find that their troubles worth more than their programming skills and how long will you put up with the troubles?

Kam - December 21, 2010

2 years past, you ain’t doin’ something open source, and you still think you should get hired? Go find another career.

200. Jase! - March 4, 2007

C++

#include
int main(int argc, char** argv)
{
for(i = 1; i

201. Jase! - March 4, 2007

#include
int main(int argc, char** argv)
{
for(i = 1; i

202. Jase! - March 4, 2007

#include
int main( int argc, char** argv)
{
for(i=1; i

203. FizzBuzz, Enterprise Edition « Quoted For Truth - March 4, 2007

[...] Those of you who have been keeping up with the programming blogosphere have probably heard of FizzBuzz by now. Well, in the spirit of this, I decided to create my own overly complicated FizzBuzz: [...]

204. Enigma - March 5, 2007

Here is a compilable COBOL version. The COMPUTE verb was strictly avoided for full verbosity, so used the DIVIDE verb instead. Also, it uses Level 88s instead of EVALUATE. Adds some code to display the number in C-style format for the golf server contest.

http://www.fileden.com/files/2007/3/4/851496/fizzbuzz-contest-2.cob

Compiles on the OpenCOBOL.org compiler.

205. Will’s Blog - FizzBuzz and Problem Finding - March 5, 2007

[...] I followed a series of links to get to Jeff Atwood’s post on Why Can’t Programmers.. Program?  Jeff references, in turn, a post by Imran on Using FizzBuzz to Find Developers who Grok Coding. [...]

206. The Chances Are Nil » FizzBusted - March 5, 2007

[...] there has been a lot of buzz about FizzBuzz but Giles Bowkett in  his post FizzBuzters hit the nail right on the head: Keep in mind, FizzBuzz [...]

207. kyu - March 5, 2007

@ Jacob I can do it without using a 3rd variable and in only 3 lines (your *How fast they do it* issue)

X=2, Y=5

x=x+y \* x=7 *\
y=x-y \* y=2 *\
x=x-y \* x=5 *\

x=5, y=2 (Hence done…)

But you would just turn me down if i presented you with this solution.

how the hell is the interviewee supposed you want him to use a 3rd variable if he knows a better way of doing it? He is supposed to read your mind?

Anyway, sorry for the disturbamce.

208. geebutbut - March 6, 2007

#include
int main()
{
printf(“%d\n”, 1);
printf(“%d\n”, 2);
printf(“Fizz\n”);
printf(“%d\n”, 4);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 7);
printf(“%d\n”, 8);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 11);
printf(“Fizz\n”);
printf(“%d\n”, 13);
printf(“%d\n”, 14);
printf(“FizzBuzz\n”);
printf(“%d\n”, 16);
printf(“%d\n”, 17);
printf(“Fizz\n”);
printf(“%d\n”, 19);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 22);
printf(“%d\n”, 23);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 26);
printf(“Fizz\n”);
printf(“%d\n”, 28);
printf(“%d\n”, 29);
printf(“FizzBuzz\n”);
printf(“%d\n”, 31);
printf(“%d\n”, 32);
printf(“Fizz\n”);
printf(“%d\n”, 34);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 37);
printf(“%d\n”, 38);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 41);
printf(“Fizz\n”);
printf(“%d\n”, 43);
printf(“%d\n”, 44);
printf(“FizzBuzz\n”);
printf(“%d\n”, 46);
printf(“%d\n”, 47);
printf(“Fizz\n”);
printf(“%d\n”, 49);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 52);
printf(“%d\n”, 53);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 56);
printf(“Fizz\n”);
printf(“%d\n”, 58);
printf(“%d\n”, 59);
printf(“FizzBuzz\n”);
printf(“%d\n”, 61);
printf(“%d\n”, 62);
printf(“Fizz\n”);
printf(“%d\n”, 64);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 67);
printf(“%d\n”, 68);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 71);
printf(“Fizz\n”);
printf(“%d\n”, 73);
printf(“%d\n”, 74);
printf(“FizzBuzz\n”);
printf(“%d\n”, 76);
printf(“%d\n”, 77);
printf(“Fizz\n”);
printf(“%d\n”, 79);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 82);
printf(“%d\n”, 83);
printf(“Fizz\n”);
printf(“Buzz\n”);
printf(“%d\n”, 86);
printf(“Fizz\n”);
printf(“%d\n”, 88);
printf(“%d\n”, 89);
printf(“FizzBuzz\n”);
printf(“%d\n”, 91);
printf(“%d\n”, 92);
printf(“Fizz\n”);
printf(“%d\n”, 94);
printf(“Buzz\n”);
printf(“Fizz\n”);
printf(“%d\n”, 97);
printf(“%d\n”, 98);
printf(“Fizz\n”);
printf(“Buzz\n”);
return 0;
}

marx - October 6, 2010

hahahahhahahahhahahhahahaha

209. Devon Sean McCullough - March 6, 2007

; Common Lisp & Emacs Lisp both:

(do ((i 1 (1+ i)))
((> i 100))
(print
(if (zerop (mod i 5))
(if (zerop (mod i 3)) ‘FizzBuzz ‘Buzz)
(if (zerop (mod i 3)) ‘Fizz i))))

; Common Lisp only:
(loop for i from 1 to 100 do (format t “~[~[FizzBuzz~:;Buzz~]~:;~[Fizz~:;~D~]~]~&” (mod i 5) (mod i 3) i))

; Emacs Lisp only:
(do ((i 1 (1+ i)))
((> i 100))
(princ (format (aref ["%d\n" "Fizz\n" "Buzz\n" "FizzBuzz\n"]
(+ (if (zerop (mod i 3)) 1 0)
(if (zerop (mod i 5)) 2 0)))
i)))

; TECO … ha ha, that way lies madness!

210. Devon Sean McCullough - March 6, 2007

; Common Lisp & Emacs Lisp both:

(do ((i 1 (1+ i)))
((> i 100))
(print
(if (zerop (mod i 5))
(if (zerop (mod i 3)) ‘FizzBuzz ‘Buzz)
(if (zerop (mod i 3)) ‘Fizz i))))

; Common Lisp only:
(loop for i from 1 to 100 do (format t “~[~[FizzBuzz~:;Buzz~]~:;~[Fizz~:;~D~]~]~&” (mod i 5) (mod i 3) i))

; Emacs Lisp only:
(do ((i 1 (1+ i)))
((> i 100))
(princ (format (aref ["%d\n" "Fizz\n" "Buzz\n" "FizzBuzz\n"]
(+ (if (zerop (mod i 3)) 1 0)
(if (zerop (mod i 5)) 2 0)))
i)))

; TECO … ha ha, that way lies madness!

211. Devon Sean McCullough - March 6, 2007

no indent
two indents

212. Devon Sean McCullough - March 6, 2007

no indent
  two &nbsp;

213. Devon Sean McCullough - March 6, 2007

no indent
  one &nbsp; and one space

214. Devon Sean McCullough - March 6, 2007

 ; Common Lisp & Emacs Lisp both:
 
 (do ((i 1 (1+ i)))
  ((> i 100))
  (print
  (if (zerop (mod i 5))
  (if (zerop (mod i 3)) ‘FizzBuzz ‘Buzz)
  (if (zerop (mod i 3)) ‘Fizz i))))
 
 ; Common Lisp only:
 (loop for i from 1 to 100 do (format t “~[~[FizzBuzz~:;Buzz~]~:;~[Fizz~:;~D~]~]~&” (mod i 5) (mod i 3) i))
 
 ; Emacs Lisp only:
 (do ((i 1 (1+ i)))
  ((> i 100))
  (princ (format (aref ["%d\n" "Fizz\n" "Buzz\n" "FizzBuzz\n"]
  (+ (if (zerop (mod i 3)) 1 0)
  (if (zerop (mod i 5)) 2 0)))
  i)))
 
 ; TECO … ha ha, that way lies madness!

215. Devon Sean McCullough - March 6, 2007

; Common Lisp & Emacs Lisp both:

(do ((i 1 (1+ i)))
    ((> i 100))
  (print
   (if (zerop (mod i 5))
       (if (zerop (mod i 3)) ‘FizzBuzz ‘Buzz)
     (if (zerop (mod i 3)) ‘Fizz i))))

; Common Lisp only:
(loop for i from 1 to 100 do (format t “~[~[FizzBuzz~:;Buzz~]~:;~[Fizz~:;~D~]~]~&” (mod i 5) (mod i 3) i))

; Emacs Lisp only:
(do ((i 1 (1+ i)))
    ((> i 100))
  (princ (format (aref ["%d\n" "Fizz\n" "Buzz\n" "FizzBuzz\n"]
                       (+ (if (zerop (mod i 3)) 1 0)
                          (if (zerop (mod i 5)) 2 0)))
                 i)))

; TECO … ha ha, that way lies madness!

216. Devon Sean McCullough - March 6, 2007

What will it take to convince them to respect fixed-width &LT

217. Devon Sean McCullough - March 6, 2007

What will it take to convince them to respect fixed-width <PRE>formatted text?
If TCP were specified the way XML is, we’d still be using Kermit.

218. Devon Sean McCullough - March 6, 2007

Sure would be nice to have a preview or a way to flush the initial losing attempts, like everyone else has. How hard can it be to render indentation? Even in a variable width context it is mighty easy to keep track of a line’s worth of overhanging character widths and line ‘em up. Let ‘em define, say, &isp; seeing as how &nbsp; does the wrong thing already and <PRE> gets hosed by every blog and mail agent… rendered, as in a glue factory, the stench ruins property values many miles downwind.

Huh, that was fun. Hiring is costlier and harder than firing but I’m not sure stupid programming tricks are much help, how well they learn matters more than what they know.

219. Steven Woods - March 6, 2007

ASP Solution:

“)
Else
If I Mod 3 = 0 Then
Response.Write(“Fizz “)
Else
If I Mod 5 = 0 Then
Response.Write(“Buzz “)
Else
Response.Write(i & ” “)
End If
End If
End If
Next
%>

220. Steven Woods - March 6, 2007

bah, it killed my code:

Try again!

<%
For i = 1 To 100

If I Mod 3 = 0 And I Mod 5 = 0 Then
Response.Write(“FizzBuzz<br /> “)
Else
If I Mod 3 = 0 Then
Response.Write(“Fizz<br /> “)
Else
If I Mod 5 = 0 Then
Response.Write(“Buzz<br /> “)
Else
Response.Write(i & “<br /> “)
End If
End If
End If
Next
%>

221. Hans Bezemer - March 6, 2007

Tiny, may be hard to comprehend, but a touch of originality?? This is done with 4tH (a forth dialect):

: zap dup 0 .r ; : fizz .” Fizz” ; : buzz .” Buzz” ; : fizzbuzz fizz buzz ;
create foo ‘ zap , ‘ fizz , ‘ buzz , ‘ fizzbuzz ,
:this foo does> >r dup 3 mod 0= 2* over 5 mod 0= + cells r> + @c execute drop ;
: bar 101 1 do i foo space loop ; bar

222. Oliodu - March 6, 2007

['FizzBuzz' if (i%15==0) else ('Fizz' if (i%3==0) else ('Buzz' if (i%5==5) else i)) for i in range(1,101)]

223. Oliodu - March 6, 2007

Sorry, a typo in previous post. Here is the right one. (Python, if you have to ask)

print ['FizzBuzz' if (i%15==0) else ('Fizz' if (i%3==0) else ('Buzz' if (i%5==0) else i)) for i in range(1,101)]

Why do any one need to do this in multiple lines?

224. stevec - March 6, 2007

I noticed almost all the fizzbuzz solutions use mod instead of addition or subtraction. I guess code size, not clock cycles is the priority for most.

225. zepto - March 7, 2007

I’ve noticed this too, and from an efficiency standpoint, doing 100+ division or modulo operations would really be frowned upon. maybe it should be changed to solve fizzbuzz without modulo.

226. zepto - March 7, 2007

looking further, we can see a pattern between
positive natural multiples of 1 (n)
multiples of 3 (t)
and multiples of five (f)
1+2(1) = 3+2(1)= 5
2+2(2) = 6+2(2)= 10
3+2(3) = 9+2(3)= 15
n = 1,2…etc
t = n + 2(n)
f = t + 2(n)
maybe someone can come up with a super elegant solution using that

227. Wayne - March 7, 2007

Fools

228. FizzBuzz « danseagrave - March 7, 2007

[...] Just a quick pointer over to more discussion of the FizzBuzz [...]

229. Michael Pohoreski - March 7, 2007

Divisions are slow, especially on embedded devices.

int i3 = 2;
int i5 = 4;

const int N = 100;
for( int i = 1; i

230. Michael Pohoreski - March 7, 2007

int i3 = 2;
int i5 = 4;

const int N = 100;
for( int i = 1; i < N; i++ )
{
if ((i3 == 0) || (i5 == 0))
{
if (i3 == 0)
{
printf( “fizz” );
i3 = 3;
}
if (i5 == 0)
{
printf( “buzz” );
i5 = 5;
}
printf( “\n” );
}
else
{
printf( “%d “, i );
}
i3–;
i5–;
}

231. Michael Pohoreski - March 7, 2007

int OUTPUT_BASE = 10;
char * Print( const int n )
{
int x = n;
bool bNegative = false;
if (x < 0)
{
bNegative = true;
x = -x; // abs|x|
}

// 2^32 = 10 digits
// 1 char for null term, 1 char for, total min = 12 chars
const int MAX_DIGITS = 16;
static char sBuf[ MAX_DIGITS ];

char *pText = sBuf + MAX_DIGITS;
*–pText = 0;

while (x >= 0)
{
int nDigit = (x % OUTPUT_BASE);
*–pText = (‘0′ + nDigit);
x -= nDigit;
x /= OUTPUT_BASE;

if (x == 0)
{
break;
}
}

if (bNegative)
{
*–pText = ‘-‘;
}

return pText;
}

232. Michael Pohoreski - March 7, 2007

Guess the double minus sign got munched when converted to html.
i.e.
* – – pText = 0;

233. Ed Courtenay - March 7, 2007

Equally, a completely over-engineered solution can be just as bad! Take this C# version as an example:

using System;

namespace FizzBuzz
{
internal class Program
{
private static void Main()
{
IFormatProvider formatProvider = new FizzBuzzFormatter();

for (int i = 1; i

234. Ed Courtenay - March 7, 2007

Attempt #2

using System;

namespace FizzBuzz
{
internal class Program
{
private static void Main()
{
IFormatProvider formatProvider = new FizzBuzzFormatter();

for (int i = 1; i < = 100; i++)
Console.WriteLine(String.Format(formatProvider, “{0:FB}”, i));

Console.ReadLine();
}
}

internal class FizzBuzzFormatter : ICustomFormatter, IFormatProvider
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null)
return String.Format(“{0}”, arg);

if (format.StartsWith(“FB”) && arg is int)
{
int val = (int) arg;
bool mod3 = val%3 == 0;
bool mod5 = val%5 == 0;

if (!mod3 && !mod5)
return arg.ToString();

string s = String.Empty;

if (mod3)
s += “Fizz”;

if (mod5)
s += “Buzz”;

return s;
}

return String.Format(“{0:” + format + “}”, arg);
}

public object GetFormat(Type formatType)
{
if (formatType == typeof (ICustomFormatter))
return this;
else
return null;
}
}
}

235. Richard - March 7, 2007

Jacob wrote (weighing in at Number 3):

Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.

If they don’t *start* with creating a third variable, you can pretty much write that person off. I’ve found that I can cut a third to half my (admittedly at that point unscreened) applicants with that question alone.

OT but one other way if they are numbers, (similary to XOR trick):
b = a + b
a = b – a
b = b – a

L. - January 10, 2012

Somehow anything can be a number … Not sure when double conversion can be smarter than actually just using the third variable .. looks a lot like fail in the end.

236. Nigel Ainscoe - March 7, 2007

Not seen a FoxPro example so:

for ln = 1 to 100
do case
case mod(ln,5) = 0 and mod(ln/3) = 0
? ‘FizzBuzz’

case mod(ln,5) = 0
? ‘Buzz’

case mod(ln/3) = 0
? ‘Fizz’

otherwise
? ln
endcase
next ln

237. Nigel Ainscoe - March 7, 2007

It stole my formatting!!

238. stevec - March 8, 2007

There are some pretty clever programmers here who have left me with some questions. Those using XOR, are you XORing the value or a pointer to the value? For those using addition/subtraction to swap, I’ll assume you only intend this for numeric values and that you probably also assumed the type would not change over the lifespan of the program (interview). But what happens if the summation overflows? Is it numerically stable for floating point values?

239. larsx2 - March 10, 2007

I just wanted to put something :P, sorry if u think that my code is not good..

# on Ruby

x = 0
while x

240. larsx2 - March 10, 2007

I just wanted to put something :P, sorry if u think that my code is not good.. XD
# on Ruby

x = 0
while x

241. Blog by Aji Issac Mathew aka AjiNIMC » Hmm… - 199 out of 200 programmers can’t program - March 10, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding – [...]

242. Mondo - March 10, 2007

This thread is a parody. A quick scan of the suggested answers reveals almost no correct responses. Did you people even read the question?

243. Chasing Mugiwara » Blog Archive » Fizz Buzz - March 11, 2007

[...] was a discussion some time ago about the lack of quality programmers applying for jobs and that even asking applicants to create basic code could sadly filter out most [...]

244. The FizzBuzz Test For Developers « Rhonda Tipton’s WebLog - March 11, 2007

[...] Topics-]Using FizzBuzz to Find DevelopersWhy Can’t Programmers.. Program?Measuring Programmer Competence via FizzBuzz [...]

245. FizzBuzz.rb - March 12, 2007

[...] my FizzBuzz solution: [...]

246. Jonas Gorauskas - March 12, 2007

In C#:

public static void Main()
{
  Console.WriteLine("FIZZBUZZ:\n");
  for (int i = 1; i
    if ((i%3==0) && (i%5==0)) {
      WL("FizzBuzz");
    } else if (i%3==0) {
      WL("Fizz");
    } else if (i%5==0) {
      WL("Buzz");
    } else {
      WL(i.ToString());
    }
  }
  Console.ReadLine();
}

247. smog - March 12, 2007

ruby (58):
1.upto(?d){|i|puts”FizzBuzz”[4&a=i*i%3*5,9-a-i**4%5]||i}

python (60):
for i in range(1,101):print”FizzBuzz”[i*i%3*4:8--i**4%5]or i

248. smog - March 12, 2007

Oops, I left out a crucial – sign in the python one:

for i in range(1,101):print”FizzBuzz”[i*i%3*4:8–-i**4%5]or i

-i**4%5 always returns 4 if i is not a multiple of 5 (0 elsewise)
(If you leave out the – it returns 1)

249. Hexten » Blog Archive » FizzBuzz in 6502 assembler - March 12, 2007

[...] FizzBuzz is an extremely basic competence test for programmers. So I thought I’d write a version extremely in BASIC. Here it is in BBC Basic’s embedded 6502 assembler. For added geek points I used a 6502 emulator written in Perl to develop it on. [...]

250. Andy Armstrong - March 12, 2007

Here it is in BBC Basic’s embedded 6502 assembler. For added geek points I used a 6502 emulator written in Perl to develop it on.

10 REM FizzBuzz in 6502 assembler
20 DIM code% 1000
30 OSWRCH = &FFEE
40 OSNEWL = &FFE7
50 work = &70
60 DIM FizzM 4 : $FizzM = “zziF”
70 DIM BuzzM 4 : $BuzzM = “zzuB”
80 FOR pass% = 0 TO 3 STEP 3
90 P%=code%
100 [opt pass%
110
120 .FizzBuzz LDA #1
130 LDX #3
140 LDY #5
150 .FB1 SEC
160 DEX
170 BNE FB2
180 JSR Fizz
190 LDX #3
200 .FB2 DEY
210 BNE FB3
220 JSR Buzz
230 LDY #5
240 .FB3 BCC FB4
250 JSR PrDecimal
260 .FB4 PHA
270 JSR OSNEWL
280 PLA
290 CLC
300 ADC #1
310 CMP #101
320 BCC FB1
330 RTS
340
350 .Fizz PHA
360 LDX #3
370 .Fizz1 LDA FizzM, X
380 JSR OSWRCH
390 DEX
400 BPL Fizz1
410 CLC
420 PLA
430 RTS
440
450 .Buzz PHA
460 LDY #3
470 .Buzz1 LDA BuzzM, Y
480 JSR OSWRCH
490 DEY
500 BPL Buzz1
510 CLC
520 PLA
530 RTS
540
550 .PrDecimal STA work
560 PHA
570 TXA
580 PHA
590 LDA #0
600 PHA
610 .PrDec0 LDX #8
620 LDA #0
630 .PrDec1 ASL work
640 ROL A
650 CMP #10
660 BCC PrDec2
670 SBC #10
680 INC work
690 .PrDec2 DEX
700 BNE PrDec1
710 CLC
720 ADC #ASC"0"
730 PHA
740 LDX work
750 BNE PrDec0
760 .PrDec3 PLA
770 BEQ PrDec4
780 JSR OSWRCH
790 JMP PrDec3
800 .PrDec4 PLA
810 TAX
820 PLA
830 RTS
840 ]
850 NEXT

251. Shawn - March 13, 2007

In the Brainfuck language:

>+++++++++[-][-]>[-]+>+>[>-]>>>
[-]>>++>[-][-]>[>>+[-]>>+>[>>-]>[-]++>->+>+>>[>>-]>[-][-]>+[-]>-]>>>[>+>+>[>-]>>>>-
]>[-]>[-]++++[-]++++[-]+
++++[-]>[>>+>+
>>[>>-]>>>-]++++[-]+++++++++[-]+++++++[-]++++++[-]++++++
++[-]+++++++++[-]++++++++
[-]++++++++[-]+++++++[-]++++++++[-]++[-]+++++++++[-]>>[>+>+>[>-]>>>>-]>>+++
+[-]++++[-]+++++[-]>[>>+>+>>[>>-]>>>-]++++[-]+++++++++[-]+++++++[-]++++++[-]++++++++++[-]+++++++[-]+++++++[-]++++++++[-]+++++++[-]+++++++[-
]++++++++[-]
+++++[-]++++
+++[-]++++++++[-]+++[
-]+++[-]+++++++++[-]+++++++[-]++++++++[-]+++++[-]+++[-]++++++++[-][-]>[
-]+>+>[>-]>>>[-]>>++>[-][-]>[>>+[-]>>+>[>>-]>[-]++>->+>+>>[>>-]>[-][-]>+[-]>-]>>>[>+>+
>[>-]>>>>-]>[-]>[-]++++[
-]++++[-]+++++[-]>[>>+>+>>[>>-]>>>-]++++[-]+++++++++[-]+++++++[-]++++++[-]
++++++++[-]+++++++++[
-]++++++++[-]++++++++[-]+++++++[-]++++++++[-]++[-]+++++++++[-]

252. Jason - March 13, 2007

Shorter Common Lisp version:
(dotimes(i 100)(format t”~A ~[Fizz~:;~]~[Buzz~:;~]~%”i(mod i 3)(mod i 5)))

74 bytes!

253. intangible - March 14, 2007

Perl:

while($i++

254. intangible - March 14, 2007

Perl again:

while($i++<100){print$i%3&&$i%5?$i:$i%3?Buzz:$i%5?Fizz:FizzBuzz,”\n”}

255. John - March 14, 2007

Another Forth solution. Not as nicely factored as the earlier one.

: .fizzbuzz ( n )
space dup 3 mod 0= over 5 mod 0= 2dup or >r
swap if .” fizz” then if .” buzz” then
r> if drop exit then . ;
: numbers 101 1 do i .fizzbuzz loop ;

256. willc2_45220 - March 15, 2007

Here’s an Applescript (8 minutes)

— fizz buzz

set holder to {}

repeat with i from 1 to 100

set flag to (i as string)

if (i / 3) = ((i / 3) as integer) then

set flag to “Fizz”

end if

if (i / 5) = ((i / 5) as integer) then

if flag = “Fizz” then
set flag to “FizzBuzz”

else
set flag to “Buzz”
end if

end if

set end of holder to flag

end repeat

holder

257. willc2_45220 - March 15, 2007

doh, tabs got stripped and the first line is a comment (DASH, DASH)

258. kurapikats - March 15, 2007

correct php code:

for ($i = 1; $i “;
} elseif ($i % 3 == 0) {
echo “fizz” . “”;
} elseif ($i % 5 == 0) {
echo “buzz” . “”;
} else {
echo $i . “”;
}
}

259. kurapikats - March 15, 2007

for ($i = 1; $i “;
} elseif ($i % 3 == 0) {
echo “fizz” . “”;
} elseif ($i % 5 == 0) {
echo “buzz” . “”;
} else {
echo $i . “”;
}
}

260. kurapikats - March 15, 2007

correct php code

for ($i = 1; $i “;
} elseif ($i % 3 == 0) {
echo “fizz” . “”;
} elseif ($i % 5 == 0) {
echo “buzz” . “”;
} else {
echo $i . “”;
}
}

261. Craig - March 15, 2007

You people writing the swap function are missing the point… I don’t think the interviewer is telling you that you’re given an integer. Rather, you need to write code that can swap two of the same type, no matter what that type is.

You would only use XOR or addition/subtraction if you’re given some integer type. Otherwise, you’d probably make use of some temp variable of the same type as those objects you are swapping.

262. Mat - March 15, 2007

Why are people posting code comments?
Get a job!

263. Subash - March 17, 2007

Apart from giving _FizzBuzz_ sort of programs, I got to interview candidates for a Senior Programmer position last month, and part of the game was to guide juniors in contacting the Database.

We got a lot of guys who had 3+ years of experience, many websites in their resumes quantifying their skills, and most of them had a good time with MySQL.

After initial screening we got three guys to the final rounds. They seemed perfect on pgming and db concepts, whizzed thru normalization concepts, different types of joins, …

But I know I’m quite sneaky. When I asked them to write an SQL query to get data from these two tables using a JOIN, my fellow interviewers sneered at my question. After intent thinking, this was what the star candidate wrote:

select * table1 inner join table2 where t1.id = t2.city

We’re still searching for a Senior programmer…

264. ore-kelate-biasa-biasa - March 19, 2007

alias otak_fizzbuz {
var %x = 1
while (%x

265. craig wilcox - March 19, 2007

What would you think of a candidate who wrote a main loop that looked something like this?:

static void Main(string[] args) {

IFizzBuzzEmitter emitter;

for(int i = 1; i

266. Alex - March 20, 2007

If I need to hire someone, I think I’ll post a trivial programming challenge on a blog, and weed out any so-called engineers incapable of taking the ten seconds needed to notice the dozens of people before them whose code was ruined by unescaped less-than signs.

As a bonus test, I’ll post an early comment under an alias in which I claim to weed out people using an even simpler test. The catch is that my expected solution is actually less than optimal, and I am potentially weeding out those smarter than myself. Those who – thinking themselves smarter – post solutions which have already been posted more than once can be safely weeded out.

I’d also like to give a special shout-out to those golfers who forget to test before posting. Golfer, meet my friend Mr. Irb.

267. Nick - March 20, 2007

“Why do people always insist on writing one-liners?”

There are other priorites in the commercial software world than mere code size, and a candidate that starts making assumptions about what those are is displaying a flaw that allows you to discount them.

Working on team software I prefer coders who remember Brian Kernighans maxim:

“Debugging someone else’s code is twice as hard as writing the code yourself.” –Brian Kernighan

268. Studiowhiz.com » Blog Archive » Unit Tests for Fizzbuzz?! - March 20, 2007

[...] anyone who has been following the FizzBuzz – saga, someone has now written a full Java implementation complete with Unit [...]

269. Buu Nguyen’s Blog » Imran on interviewing programmers - March 21, 2007

[...] this to see how Imran tests his interviewees.  Being curious if the test had some tricks which [...]

270. Loosely Typed in Ohio. » FizzBuzz…The SQL Version - March 21, 2007

[...] tech blogosphere was humming last week about FizzBuzz, a simple test to figure out if your candidate can write even a trivial program. Write a program [...]

271. Maan’s Blog » Archives » FizzBuzz - March 22, 2007

[...] is a quick code I wrote to try myself with an interview coding question from this article. Basically it took me 10 min to write the whole thing (I tried to write it as neat and as elegant [...]

272. AndreasB - March 22, 2007

perl while($i++

273. ka - March 22, 2007

I’m 4 and I did this

what a bunch of idiots

penis size = 111 in.

274. ka - March 22, 2007

the kicker about all this is that you’re using an online ‘out of the box’ blogging site to ‘bitch’ about people that can’t program…

Like a fucking blog would be that hard to write yourself :P

you don’t even have your own install of WP, you’re using THEIR service…

l4m3

——————————————
on a more respectful note:

I’m the Lead Developer (don’t consider myself a programmer) with 7 years of experience with so many awards under my belt it would crash your *insert output environment here* if you tried to loop through them.

I could easily do this, however as a web developer looking to hire someone, I would be much more worried about ‘other’ things then things I can essentially teach them.

* how well do they communicate?
* what do they understand about the business side of their particular field? things such as ROI (Clients don’t want to hear b/s about programming, they want to know how it makes them money or how they can get a return on their technology investment)
* are they quick learners?
* are they overall balanced with other tasks? (it would suck to hire someone who is so smart they can program fizzbuzz but can’t do anything else).
* will they get along with everyone else they need to work with

Those (imo) are much more pressing things to evaluate in an interview then some task of measuring ones penis size.

Ask some basic programming questions.

* What can you tell me about OOP?
* What is the ‘proper’ way to insert data into a database?

etc etc etc.

Would be much more profitable in finding a ‘good programmer’ who might also be a great person to work with.

275. mv - March 24, 2007

My own experience working with new hires fresh from school is that they very often can do the algorithmic stuff but fall down on the things that make ‘real world’ programming different from school: changing requirements, change control, evaluating multiple designs and communicating their thought processes clearly.

And follow-through: in the academic environment, 90% gets a ‘A’, you work alone, and you almost never revisit the issue. Would that it were that way in the commercial environment!

276. Jon - March 26, 2007

To all those self-proclaimed experts who think you shouldn’t hire people who don’t XOR to swap variables, I’d suggest that a) you devalue the importance of optimisation as a hiring criteria, and b) you read the comp.lang.c. faq a few more times: http://c-faq.com/expr/xorswapexpr.html

277. beton - March 28, 2007

beat me, please B)

278. find » Using FizzBuzz to Find Developers who Grok Coding - April 1, 2007

[...] Original post by tickletux [...]

279. Royal Miah - April 3, 2007

ben we are talking about memory level swaping not high level.

280. forward - April 4, 2007

Want to know why this subject is so popular?

Because it makes everyone who thinks they are a programmer feel good, and gives them a sense of worth (because if you read stuff like this, you most likely can do the test).

I think most people who are computer programmers were kind of social misfits originally (and probably still are (I am including myself)). So nothing like a simple test to give a programmer a sense of self worth.

Same principle applies to those TV shows that ask people on the street a stupid question that they get wrong. Everyone at home gets to sit there and say, “Man, that guy is stupid, and man, am I smart!”.

Yeah, yeah…. we are all smart. Now get back to work :).

(wanna a real test? program something that when compiled, produces a Ferarri :)…. im still working on that one….

281. World of Ruby Indonesia fizzbuzz, dibuang sayang « - April 5, 2007

[...] bisa nggak? h eh eh 5:28:11 PM dewa_error1: search fizzbuzz di google :-) 5:28:37 PM dewa_error1: http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ 5:29:30 PM dewa_error1: “Want to know something scary ? – the majority of comp sci graduates [...]

282. kost BebiX - April 5, 2007

Jacob, about your problem about swapping variables values.
I know the method with

a = a + b;
b = a – b;
a = a – b;

but it works slower then just

c = a; a = b; b = c;

So it’s better to use second one.

283. Syam Kumar R. - April 6, 2007

<?php
for($i =1; $i < 101; $i++)
{
if($i % 3 == 0) print “Fizz”;
if($i % 5 == 0) print “Buzz”;
if($i % 3 != 0 && $i % 5 != 0) print $i;
print “<br />”;
}
?>

284. PsyckBoy - April 10, 2007

I’m still working on the solution in INTERCAL. I’ll be done any day now.

285. Army1987 - April 15, 2007

What the hell?

#include
#define MAX 100
#define FIZZ 3
#define BUZZ 5

void fizzbuzz(int n)
{
if (n%FIZZ == 0)
printf(“Fizz”);
if (n%BUZZ == 0)
printf(“Buzz”);
if (n%FIZZ && n%BUZZ)
printf(“%d”, n);
}

int main(void)
{
int i;
for (i=1; i

286. phr - April 15, 2007

My preferred (extensible) python fizzbuzz:

fizzbuzz = ((3, ‘Fizz’), (5, ‘Buzz’))
def fizzify(n):
fb = ”.join(b for a,b in fizzbuzz if n%a == 0)
return fb or str(n)

for i in xrange(1,100): print fizzify(i)

I hope I didn’t mess this up ;-)

287. phr - April 15, 2007

Heh, I did mess it up (aside from the comment function clobbering python indentation). That should have said xrange(1,101) in order to print the numbers up to and including 100.

288. Greg - April 16, 2007

I read about half the comments and gave up. All these guys who say “this is too hard/unrealistic/stressful in an interview”.

YOU are the kind of programmer that people are talking about here. I wrote the VB 6.0 implementation of this in 22 seconds.

The point is extremely valid. This test is so simple, if you can’t do it, you don’t deserve a programming job.

289. Bart - April 16, 2007

I worked at a small software consultancy company where we had a similar test. We had a laptop ready and asked the candidate to write some simple code – similar to the fizzbuzz test.

One thing we were looking for: the speed at which the code was typed.

“Experienced Programmer”, typing with two fingers and looking up every single key? I don’t think so…

290. bruno - April 16, 2007

Just to answer to comment #3 from Jacob: some languages are smart enough to let you swap 2 vars without a temporary one. The following works at least with Python and Ruby:

a, b = b, a

FWIW, I’d probably rule off someone claiming experience with one of these languages and using a temporary variable !-)

291. qebab - April 17, 2007

I’m self taught, and only know a bit of python. I don’t even know how to escape the lesser than operator in html! However, this is just a test of logical thinking, and it was easy.
Pseudo code would be f. ex.

for every number between 1 and 100 (100 included)
output = empty string
if number mod 3 is 0: output = output + Fizz
if number mod 5 is 0: output = output + Buzz
if output is an empty string: output = number
print output

I wrote a ‘golfed’ version but changed it to a function after some comments here, so let’s call i t a golfed function.
def fizzbuzz(limit,tests,words)
i=1
while limit>i:print words[0]*(i%tests[0]==0)+words[1]*(i%tests[1]==0)or i;i+=1

The golfed version was simply:
i=1
while 101>i:print’Fizz’*(i%3==0)+’Buzz’*(i%5==0)or i;i+=1

As aforementioned, I’ve got no idea how to escape lesser than in html, but if I did, I’d change the ==0 to lesser than 1.

I liked the test, and I agree that if you can’t do it, you’re probably not suited to program for a living.

292. Basilisk - April 18, 2007

Maybe it’s just how my mind really works, but here’s a backwards-thinking Python solution:

def fizzbuzz(n):
m3 = n % 3
m5 = n % 5
m_both = m3 or m5
if not m_both:
return “Fizz-Buzz”
elif not m5:
return “Buzz”
elif not m3:
return “Fizz”
else:
return n

for x in range(1, 101):
print fizzbuzz(x)

Silly, eh?

293. Fizz Buzz « My raves, my rants, a piece of me - April 19, 2007

[...] using-fizzbuzz-to-find-developers-who-grok-coding Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” [...]

294. Halop - April 20, 2007

Well, in our case the problem was not about programming skills. I wouldnt mention this if it was a single case, but it seems quite common. Not long ago we hired a ruby developer who i think actually was dreaming in code… I swear i have never met a better coder in my life. Whatever the problem was he could come up with the solution right away, then two minutes later he optimized the code to a hm. “one-liner”. But when it came to actual work, this guy could not finish a single job on time. We used to give him deadlines of several days less than the actual deadline just to be sure that it will be done. And even this didnt work sometimes, and of course it was always someone elses fault. Then add to this, that he changed the look and function of the projects when he felt neccessary (and he usually did :), because the client is ofcourse stupid and doest know what he really wants. The code he produced at the end was always clean, efficient – perfect in a sense, but well, we got fed up with this everyone being stupid and he knowing everything better attitude, and the constant delays, and the constant “surprises”, and that we had to literaly force him to do what we are payed for and not what he likes better. My point is, that being a good coder is only one part of it, and – well, for me at least – being able to actually do a job is just as important. So if i have to choose between a coder who does FizzBuzz in 20 seconds and says everyone above 30secs is stupid and Fizzbuzz is a stupid game too and he could come up with a better one anytime, and one who does it in 2 minutes and then waits for the next question, well i would stick with the second one. ;)

295. ka - April 20, 2007

@Halop

This is exactly why companies have HR depts and programmers have no business hiring someone, only recommending them ;)

296. Anson - April 21, 2007

I’m surprised there haven’t been more Perl solutions.

foreach ((1..100)) {
$fizzbuzz = “”;
$_ % 3 eq 0 and $fizzbuzz = “Fizz”;
$_ % 5 eq 0 and $fizzbuzz .= “Buzz”;
$fizzbuzz and print “$fizzbuzz\n” or print “$_\n”;
}

297. Anson - April 21, 2007

And here’s one with no division done:

$f = $b = 0;
foreach ((1..100)) {
++$f eq 3 and print “Fizz” and $f = 0;
++$b eq 5 and print “Buzz” and $b = 0;
$f ne 0 and $b ne 0 and print “$_”;
print “\n”;
}

298. Jan - April 24, 2007

ummmm… if you’re looking for “Developers”, then this sort of question is rather pointless. Sure, it may winnow out some obviously unskilled candidates but you will also dismiss many talented people who can help you greatly.

There is a huge difference between a developer and a programmer. A developer’s overall job is much larger, and much more complex. The programmer’s individual tasks may be complex, and that’s where you need rigorous skills, but of far more use is the ability to design and implement and learn on the job.

I see this sort of thing as programmer silliness. It’s merely programmer elitism: if you can’t do x then you’re not as good as me. Very silly.

Each person in a team brings different skills. In some area that person will probably be _better_ than you. They may advance your business or project in ways that you didn’t even anticipate, but you won’t find out because you’ve abitrarily rejected them based on a very piddling test.

Instead of finding the ideal geek, I would try to find the person who can mix in well and who knows how to _learn_ what s/he needs to know.

Kam - December 21, 2010

you’re Dev is someone else’s systems analyst. and gets paid LOT LESS than the coder.

299. Fried Chicken Arcade - April 28, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding This simple test apparently can weed out those who cannot code. Try it for yourself! (tags: coding internet) [...]

300. simple singularities » FizzBuzz Problem - May 11, 2007
301. JavaSPEKTRUM Blogosphäre » Blog Archiv » Blogosphäre (aus JavaSPEKTRUM 03/07) - May 15, 2007

[...] zu häufig die Probleme schon bei den absoluten Grundlagen beginnen und schlägt einen trivialen Programmiertest namens FizzBuzz als erste Hürde für ein Gespräch vor. Die Aufgabe: Schreiben Sie ein Programm, das die Zahlen [...]

302. Solving the Fizz-Buzz Question | FuCoder.com - May 17, 2007

[...] quoted Irman’s FizzBuzz question, a trivial programming problem but surprisingly has stumbled many job applicants. Here is the [...]

303. abu ameerah - May 18, 2007

FizzBuzz is awesome!

304. abaqueiro - May 19, 2007
305. Best of Feeds - 29 links - blogging, seo, programming, search, google, humor « //engtech - internet duct tape - May 21, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding (tickletux.wordpress.com, 4 saves) [...]

306. pixolut - May 22, 2007

At Pixolut we do a 6 hour practical exam with only a single UML diagram as the question. “Implement this”.

The exam requires unit tests be written for parts of the system that can be tested and the candidate should use an ‘inversion of control’ pattern to create mock objects to test the abstract functionality.

We allow any modern OO style language that has a test framework (pretty much any modern language today) and the programmer can bring in any materials they want and access the internet as much as they need.

This exam applies accross language barriers (spoken and programmed!) and successfully sorts out the fluff. The good thing though, is that it is practical and as such illustrates the shades of grey which defines an individual.

Example: I had someone take the exam and finish it in 3 hours instead of 6. Some code was a bit sloppy but the solution worked perfectly. This result showed me exactly where I would have to keep an eye out for issues and also where his strengths were.

Joe Cincotta: blog.pixolut.com

307. Dragon’s Notes » The FizzBuzz Test - May 26, 2007

[...] ran across this blog post the other day, while browsing around some programming sites after making an update to CharacterGen [...]

308. Alfred Kayser - May 31, 2007

One of the most optimal solutions in C:
#include
main() {
for(int i=1;i

309. Alfred Kayser - May 31, 2007

Another try:
#include <stdio.h>
main() {
for(int i=1;i%lt;=100;i++) {
printf(i%15?i%3?i%5?”%i\n”:”Buzz\n”:”Fizz\n”:”FizzBuzz\n”);
}
}

310. Alfred Kayser - May 31, 2007

Another try:
#include <stdio.h>
main() {
  for(int i=1;i<=100;i++) {
    printf(i%15?i%3?i%5?”%i\n”:”Buzz\n”:”Fizz\n”:”FizzBuzz\n”);
  }
}

So, the hard part is not coding it, but posting the code as a comment on a blog. ;-)

311. John - May 31, 2007

I think a lot of you are missing the point. its not about code elegance or refactoring, its about the simple duplicate line of code staring you in the face. How do I know? Well I answered it wrong too ;). Its so easy its staring you right in the face:

for ( int i = 1 ; i

312. John - May 31, 2007

for ( int i = 1 ; i <= 100; i ++ ) {
if (i % 3 == 0 ) print “Fizz”;
if (i % 5 == 0 ) print “Buzz”;
else print i;
// formatting purposes
print “\n”;
}

313. Jason - May 31, 2007

HAI
CAN HAS STDIO?
I HAS A VAR

IM IN YR LOOP
UP VAR!!1
IS VAR OVAR 3 LIEK 0?
VISIBLE “FIZZ”
IS VAR OVAR 5 LIEK 0?
VISIBLE “BUZZ”
IS VAR OVAR 3 LIEK 0 AND VAR OVAR 5 LIEK 0?
VISIBLE “FIZZBUZZ”
IZ VAR BIGR THAN 100? GTFO. KTHX
IM OUTTA YR LOOP
KTHXBYE

314. Damian Brasher - June 1, 2007

#!/bin/bash
i=”1″
n=”0″
t=”0″
while [ $i -lt 101 ];
do
n=$[$i%3]
t=$[$i%5]
if ((“$t” == 0)) && ((“$n” == 0)); then
echo “FizzBuzz”
elif [ $n == 0 ]; then
echo “Fizz”
elif [ $t == 0 ]; then
echo “Buzz”
else
echo “$i”
fi
i=$[$i+1]
done
exit 0

315. Hugo Mills - June 1, 2007

I’m amazed that nobody’s done it in the paragon of languages…

/Test {
3 2 roll
exch mod 0 eq
{ show true }
{ pop false }
ifelse
} bind def

/mm { 25.4 div 72 mul } bind def

/Helvetica findfont
12 scalefont setfont
72 297 mm 72 sub translate

1 1 100 {
dup 1 sub dup 50 idiv 288 mul exch 50 mod 14 mul neg moveto
dup false exch
dup (Fizz ) 3 Test
exch (Buzz) 5 Test
or or not { 3 string cvs show true } if
pop
} for

showpage

316. PHoog - June 4, 2007

Console.WriteLine(“1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n”);

317. Petal and Paws - June 4, 2007

How to Fizzbuzz…

Okie, so it’s simple enough… right?
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 …

318. Robspages - June 6, 2007

PHP

for($i=1; $i < 101; $i++){
switch(true){
case ($i % 3 == 0 && $i % 5 == 0):
echo “FizzBuzz <br/&grt;”;
break;
case ($i % 3 == 0):
echo “Fizz <br/&grt;”;
break;
case ($i % 5 == 0):
echo “Buzz <br/&grt;”;
break;
default:
echo $i . ” <br/&grt;”;
break;
}
}

319. Robspages - June 6, 2007

gah – botched the >

320. Alex Oren - June 6, 2007

C++ template metaprogramming.
Everything is calculated at compile time and the result is just a series of printf() calls.

////////////////////////////////////////////////////////////////

#include

#if defined(_MSC_VER) && _MSC_VER >= 1300
#define inline __forceinline
#endif

////////////////////////////////////////////////////////////////

template struct fb
{ static inline void Do() { printf(“%i\n”, I); } };

template struct fb
{ static inline void Do() { printf(“fizzbuzz\n”); } };

template struct fb
{ static inline void Do() { printf(“fizz\n”); } };

template struct fb
{ static inline void Do() { printf(“buzz\n”); } };

template struct loop
{ static inline void Do()
{ loop::Do(); fb::Do(); }
};

template struct loop
{ static inline void Do() {} };

////////////////////////////////////////////////////////////////

int main(int argc, char* argv[])
{
loop::Do();
return 0;
}

321. Alex Oren - June 6, 2007

Trying again:

////////////////////////////////////////////////////////////////

#include <stdio.h>

#if defined(_MSC_VER) && _MSC_VER >= 1300
#define inline __forceinline
#endif

////////////////////////////////////////////////////////////////

template<bool mod3, bool mod5, int I> struct fb
{ static inline void Do() { printf(“%i\n”, I); } };

template<int I> struct fb<true, true, I>
{ static inline void Do() { printf(“fizzbuzz\n”); } };

template<int I> struct fb<true, false, I>
{ static inline void Do() { printf(“fizz\n”); } };

template<int I> struct fb<false, true, I>
{ static inline void Do() { printf(“buzz\n”); } };

template<int I> struct loop
{ static inline void Do()
{ loop<I-1>::Do(); fb<I%3==0, I%5==0, I>::Do(); }
};

template<> struct loop<0>
{ static inline void Do() {} };

////////////////////////////////////////////////////////////////

int main(int argc, char* argv[])
{
loop<100>::Do();
return 0;
}

////////////////////////////////////////////////////////////////

322. Angus Lepper - June 6, 2007

C99:

#include <stdio.h>
#define p(t,s) if(i%t)printf(“s”)
void main(){for(int i=1;i<101;++i){p(15,Fizz-Buzz)&&continue;p(3,Fizz);p(5,Buzz);}}

I’m sure it’s possible to get it shorter but I’m new to this lark!

323. Geek School » Get Hired With FizzBuzz - June 13, 2007

[...] programming problem has been discussed a lot lately because apparently a lot of programmers can’t do it. I’ve never been asked this particular question in an interview; I had never heard of it [...]

324. whoknows - June 16, 2007

i see assembly is underrepresented. :(

i’m very much a beginner with arm asm and coding in general but wanted to make up for the underrepresentation of asm.. no assembler right now so i’ll give assembled code with arbitrary addresses (and of course untested). the systemcall used is only good for some systems, sry for that. :)

hey such a short code in hex.
FF 40 2D E9 01 00 A0 E3 01 10 A0 E3 94 A0 9F E5
33 00 00 EB 00 40 9A E5 03 00 51 E3 78 40 9F 05
06 00 51 E3 70 40 9F 05 09 00 51 E3 68 40 9F 05
0C 00 51 E3 60 40 9F 05 05 00 51 E3 5C 40 9F 05
0A 00 51 E3 54 40 9F 05 0F 00 51 E3 50 40 9F 05
00 50 A0 E1 01 60 A0 E1 04 10 A0 E1 00 20 A0 E3
00 30 A0 E3 00 00 A0 E3 3C 70 9F E5 0F E0 A0 E1
07 F0 A0 E1 05 00 A0 E1 06 10 A0 E1 01 10 81 E2
01 00 80 E2 10 00 51 E3 01 10 A0 23 64 00 50 E3
DE FF FF 3A FF 80 BD E8 00 00 00 00 B8 00 00 00
C4 00 00 00 D0 00 00 00 B0 00 00 00 38 BB 00 F0
00 00 00 00 00 00 00 00 42 00 55 00 5A 00 5A 00
00 00 00 00 46 00 49 00 5A 00 5A 00 00 00 00 00
46 00 49 00 5A 00 5A 00 42 00 55 00 5A 00 5A 00
00 00 00 00 1F 40 2D E9 0F 20 01 E2 0A 00 52 E3
06 10 81 22 F0 20 01 E2 22 22 A0 E1 01 20 42 22
06 00 A0 E3 92 00 00 E0 01 00 80 E0 0F 20 00 E2
30 20 82 E2 F0 30 00 E2 23 32 A0 E1 30 30 83 E2
00 4F 80 E2 24 44 A0 E1 30 40 84 E2 02 20 CA E4
02 30 CA E4 00 40 CA E5 04 A0 4A E2 1F 80 BD E8

ok..for better readibility:

loc_start
STMFD, SP! {R0-R7, LR}
MOV R0, #1
MOV R1, #1
LDR R10, [PC,#94]

loc_0
BL loc_3
LDR R4, [R10]
CMP R1, #3
LDREQ R4, [PC,#78]
CMP R1, #6
LDREQ R4, [PC,#70]
CMP R1, #9
LDREQ R4, [PC,#68]
CMP R1, #0xC
LDREQ R4, [PC,#60]
CMP R1, #5
LDREQ R4, [PC,#5C]
CMP R1, #0xA
LDREQ R4, [PC,#54]
CMP R1, #0xF
LDREQ R4, [PC,#50]
MOV R5, R0
MOV R6, R1
MOV R1, R4
MOV R2, #0
MOV R3, #0
MOV R0, #0
LDR R7, =0xF000BB38
MOV LR, PC
MOV PC, R7
MOV R0, R5
MOV R1, R6
ADD R1, R1, #1
ADD R0, R0, #1
CMP R1, #0x10
MOVCS R1, #1
CMP R0, #0x64
BCC loc_0
LDMFD, SP! {R0-R7, PC}

loc_3: crappy converting so it’ll stay in hex. :)

325. whoknows - June 16, 2007

pressed enter too fast..i mean that part is very much hard coded and so isnt nice :)

326. Anonymous - June 17, 2007

#include

int main(void)
{
int loopvar = 0; // Used to
for(loopvar = 1; loopvar

327. Anonymous - June 17, 2007

#include
int main(void)
{
int tmpvar = 0;
for(tmpvar = 1; tmpvar

328. Solarvoid » Blog Archive » First Challenge - June 28, 2007

[...] decided to start off the challenges with a dirt simple challenge: the FizzBuzz problem. Write a program that prints the numbers from 1 to 100. But for multiples of three print [...]

329. applicant tracking system - June 29, 2007

applicant tracking system

Hi. Thanks for the good read.

330. Shypy - July 5, 2007

Its amazing to see how many solutions here are incorrect too

331. tired old smart-ass programmer - July 11, 2007

one line javascript, pastable into a url (with bonus points for lack of whitespace and nested ?: usage):

javascript:for(x=0;x

332. tired old smart-ass programmer - July 11, 2007

one more time, to bypass the greater than/less than censors:

javascript:for(x=1;x!=101;x++)document.write((x%3?x%5?x:’Buzz':x%5?’Fizz':’FizzBuzz’)+’ ‘)

333. tired old smart-ass programmer - July 11, 2007

wow getting code to run after all the tick replacing wordpress does is difficult.

once more then, saving one more byte:

javascript:for(x=0;++x

334. stupid code tricks - July 11, 2007

4s a charm?

javascript:for(x=0;++x!=101;)document.write((x%3?x%5?x:”Buzz”:x%5?”Fizz”:”FizzBuzz”)+” “)

335. stupid code tricks - July 11, 2007

To Jan #298:

If a developer or whoever couldn’t write this code, I wouldn’t want them working with me.

It’s super dirt easy. Maybe the ‘developer’ or whoever you would let through shouldn’t be in tech.

I mean, what test should we use to weed out the ones who need handholding from the competant?

print your name three times?! set a variable called “i” to 500?

336. Sn0rt - July 12, 2007

Ummm, Brian Pew, your code:

void XORSwap(void *x, void *y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}

is even more dangerous than the dereferenced void pointers. Consider what happens if x == y. The XOR statements basicly zero out both pointers. Danger!!

337. Tobin Harris - July 21, 2007

Lol, intresting test question. I noticed most ruby examples just show off Ruby’s terse format. How about something a little more readable?

(1..100).each do |i|
print “\n#{i}”
print ” Fizz” if i % 3 == 0
print ” Buzz” if i % 5 == 0
end

338. Paw Prints » Blog Archive » In Denial - August 7, 2007

[...] among software practioners. Examples of the kind of thing I’m referring to can be found here and here. My personal experience would back up the sentiments that are expressed in these postings [...]

339. Cheez - August 15, 2007

76 bytes of PHP ;)

<?for(;++$n<101;){$e=($n%3)?”:fizz;$e.=($n%5)?”:buzz;echo($e)?$e:$n,’ ‘;}

340. toxik - August 15, 2007

Python isn’t readable. I have proof, and I beat Cheez in a verbose language, 70 bytes without the (unneeded) trailing newline:

for i in range(1,101):print(“Fizz”[:(i%3<1)*9]+”Buzz”[:(i%5<1)*9])or i

341. Definition of Information :: another one bites ... - August 22, 2007

[...] if you are a prospective developer please read  http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/. If you can not complete this test in 10 minute, go read a book on programming and figure it [...]

342. Sam - August 23, 2007

Without knowing PL/SQL beforehand (because heck — no one’s tried it in SQL), in under ten minutes and access to the internet:

set echo on;
drop table TEMP;
create table TEMP
(text char(55), col2 number(4));
/
BEGIN
FOR i IN 1..100 LOOP
IF MOD(i,15) = 0 THEN
INSERT INTO temp VALUES (‘fizzbuzz’, NULL);
ELSE IF MOD(i, 3) = 0 THEN
INSERT INTO temp VALUES (‘fizz’, NULL);
ELSE IF MOD(i, 5) = 0 THEN
INSERT INTO temp VALUES (‘buzz’, NULL);
ELSE
INSERT INTO temp VALUES (”, i);
END IF;
END LOOP;
COMMIT;
END;
/
select * from TEMP;

343. Four Points Cardinal » Blog Archive » FizzBuzz - August 23, 2007

[...] Using FizzBuzz to Find Developers who Grok Coding [...]

344. Old Wolf - August 24, 2007

Most posters seem to have missed the point of the variable swap test. Anyone who writes an obfuscated fragile non-portable hack fails, e.g. Brian Pew whose code doesn’t even compile, let alone work. Assuming the language doesn’t have a swap facility (i.e. pretty much limited to C or BASIC), using the temporary variable is the best solution bar none.

345. nomen - August 24, 2007

Ruby:

(1..100).each do |line|
if line % 3 == 0
print “Fizz”
end
if line % 5 == 0
print “Buzz”
end
print line unless line % 3 == 0 or line % 5 == 0
print “\n”
end

346. Dlareg - August 24, 2007

1 a = (1…101).to_a
2 changes = {5 => “Buzz”, 3=> “Fizz”}
3 changes.each do |number,word|
4 n=a.size
5 (n/number).times do |i|
6 pos = (i*number)-1
7 if a[pos].is_a? Fixnum
8 a[pos]=word+’ ‘
9 else
10 a[pos] = a[pos][0..-2]+word+’ ‘
11 end
12 end
13 end
14 p a
~

347. SlyEcho - August 24, 2007

Assembles with FASM and works in DOS (and Windows too, even Vista):

org 100h

mov cx, 0
foo:
inc cx
mov ax, cx

mov bl, 100
div bl
add al, 30h
mov [num], al
mov al, ah
xor ah, ah

mov bl, 10
div bl
add al, 30h
mov [num+1], al
add ah, 30h
mov [num+2], ah

mov dx, num
mov ah, 09h
int 21h

mov ax, cx
mov bl, 3
div bl
or ah, ah
jnz nofizz

mov dx, fizz
mov ah, 09h
int 21h
nofizz:

mov ax, cx
mov bl, 5
div bl
or ah, ah
jnz nobuzz

mov dx, buzz
mov ah, 09h
int 21h
nobuzz:

mov dx, eol
mov ah, 09h
int 21h

cmp cx, 100
jnz foo

mov ax, 4c00h
int 21h

num db ‘xxx:$’
fizz db ‘Fizz$’
buzz db ‘Buzz$’
eol db 0dh, 0ah, 24h

348. ACL - August 24, 2007

In tsql

declare @counter int
declare @output varchar(15)
set @counter = 1
while @counter < 101
begin
set @output = ”
if @counter % 3 = 0
begin
set @output = ‘Fizz’
end
if @counter % 5 = 0
begin
set @output = @output + ‘Buzz’
end
if @output = ”
begin
set @output = @counter
end
print @output
set @counter = @counter + 1
end

349. ACL - August 24, 2007

Where’s my indentation :)

350. Verm - August 25, 2007

There are way too many people here who think tests like these would have absolute answers.

It doesn’t really matter what exactly they come up with. There is a logical way to build a FizzBuzz program. You start with the loop, then put in the checks, using mod to check for multiples. If they start that way, fine, even if they forget to worry about multiples of 15.

Same with swapping two variables, except there’s not really any logical bugs to make there. If they define a third variable, assign the first number to it, assign the second to the first, and assign the third to the first, well, they seem to have a firm grasp on the concept.

If, instead of doing it sanely, they come out with some one-line amazing thing, they they’re either a very good programmer, or a moderately good one who’s read this page, so that’s fine too. (As an aside, I immediately thought of list($a,$b) = array($a,$b) in PHP too, like some others on this page. :) I do know of the XOR trick for C and other languages, but wouldn’t trust myself to be able to replicate it correctly in an interview. )

It’s when the person being interviewed doesn’t appear to know what to do or how to start that’s the warning sign.

351. L - August 25, 2007

Whoever wrote the KTHXBYE version… Nice job! Though it seems to fail to print the number if it isn’t one of the fizzbuzz numbers.

352. Ivan Tikhonov - August 27, 2007

: fizz 1+ .” fizz ” ;
: bazz 1+ .” bazz ” ;
: fizzbazz 1+ .” fizzbazz ” ;
: n 1+ dup . ;
: bange n n fizz n bazz fizz n n fizz bazz ;
: bang bange n fizz n n fizzbazz ;

0 bang bang bang bang bang bang bange drop cr bye

Yep, you need no modulus checking for fizzbuzz.

353. ACL - August 29, 2007

Another one in c# ala the Forth example above:

public delegate void Function(ref int x);
public static Function MakeFizzBuzz(string word)
{
if (word == “n”)
return delegate(ref int x)
{
x++;
Console.WriteLine(x);
};
else
return delegate(ref int x)
{
x++;
Console.WriteLine(word);
};
}
static Function n = MakeFizzBuzz(“n”);
static Function fizz = MakeFizzBuzz(“Fizz”);
static Function buzz = MakeFizzBuzz(“Buzz”);
static Function fizzbuzz = MakeFizzBuzz(“FizzBuzz”);

public static void Ten(ref int x)
{
n(ref x);n(ref x);fizz(ref x);n(ref x);buzz(ref x);
fizz(ref x);n(ref x);n(ref x);fizz(ref x);buzz(ref x);
}

public static void Fifteen(ref int x)
{
Ten(ref x);n(ref x);fizz(ref x);n(ref x);n(ref x);fizzbuzz(ref x);
}
static void Main(string[] args)
{
int x = 0;
Fifteen(ref x);Fifteen(ref x);Fifteen(ref x);Fifteen(ref x);
Fifteen(ref x);Fifteen(ref x);Ten(ref x);
Console.ReadLine();
}

354. leymoo - September 13, 2007

Surely:

1. If you were hiring for a *programmer*, you’d want them to bang out the code easily, much like people above me have done.

2. If you were hiring for a *developer*, you’d want them to ask “ok, what would you like me to do? I can code a short term quick solution or I can create a more flexible long term solution if you require. Would you be looking to possibly extend fizzbuzz in the future? Is there any more information you could provide?”
Take the information, THEN code a solution.

355. Imran - September 13, 2007

I am a programmer/developer with a masters degree and an years experience in system programming . I will take some time to write that code .. arnd 5 mins.

But if u give me question with some logic, which I know, I still take some time. Partly bcz I haven’t practised writing programs on papers. Rather I can write those on a text editor faster.

356. def essays(codecraft) » Hiring programmers - September 16, 2007

[...] looking for ways to improve the screening of candidates. There are interview coding tests link the FizzBuzz test. Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” [...]

357. martinus - October 1, 2007

% Erlang solution
-module(fb).
-export([fb/0]).

fb() ->
fb(1).

% iterate
fb(101) ->
ok.
fb(X) ->
pr(X),
fb(X+1).

% print
pr(X) when X rem 15 =:= 0 ->
io:format(“FizzBuzz\n”);
pr(X) when X rem 3 =:= 0 ->
io:format(“Fizz\n”);
pr(X) when X rem 5 =:= 0 ->
io:format(“Buzz\n”);
pr(X) ->
io:format(“~w\n”, [X]).

358. martinus - October 1, 2007

# Ruby solution
(1..100).each do |i|
if (i % (3*5) == 0)
puts “FizzBuzz”
elsif (i % 5 == 0)
puts “Buzz”
elsif (i % 3 == 0)
puts “Fizz”
else
puts i
end
end

359. martinus - October 1, 2007

The most important question is to ask them what they think about the code they have just written, this way you can find out how good he really is. E.g. about the ruby solution I would say something like this:

* No unit tests for the code, which is bad.
* the i%(3*5) is not obvious, needs a comment.
* Solution is not very general, but with the given information it is useless to generalize it more because we don’t know what generalization will be necessary in future.
* solution is not reusable because not inside a class
* hardcoded numbers are bad
* performance could be optimized by reordering statements, i%3 is the most often case.
* performance of % and if statement is probably irrelevant because io is usually the limiting factor.
* purpose of the code is unknown.

L. - January 11, 2012

not reusable because not inside a class ?? god bless brainwashing.

Performance of % and if statement is extremely relevant because there will be no IO for this exercise.

360. Drew Peacock - October 3, 2007

I refuse to believe that anyone with even the most casual understanding of a language would be unable to make their own FizzBuzz. Surely this is about how you work, and in which case I’d not want to team up with the people above who treated it as a challenge to create brilliantly terse but wholly impenetrable one-liners. Great if you’re running low on hard drive space, I guess, but not so great if you want your fellow developers to like you…

Pascal


var
N: Integer; S: String;

for N := 1 to 100 do begin
S := '';
if N mod 3 = 0 then begin
S := 'Fizz';
end;
if N mod 5 = 0 then begin
S := S + 'Buzz';
end;
if (N mod 3 > 0) and (N mod 5 > 0) then begin
S := IntToStr(N);
end;
WriteLn(S);
end;

361. FizzBuzz in Factor « Shellfish Jeans - October 7, 2007

[...] Now if you don’t know what FizzBuzz is, take a look at this: Using Fizzbuzz to find developers who Grok coding [...]

362. 100 Resources to Attract, Retain and Utilize Rock Star Programmers | MT-Soft Website Development - October 18, 2007

[...] Using FizzBuzz to Find Developers Who Grok Coding: This method recommends testing your candidates with a lowball problem to find out their competency. [...]

363. Scott Hanselman's Computer Zen - The Weekly Source Code 9 - WideFinder Edition - October 23, 2007

[...] many folks are focusing on Item #5. Either way, it’s a heck of a lot more interesting problem than FizzBuzz and worth adding to your interview arsenal [...]

364. Terry Smith - October 24, 2007

Ruby

(1..100).each{|n|
puts n unless n % 3 ==0 unless n % 5 == 0
puts “Fizz” if n % 3 ==0 unless n % 5 == 0
puts “Buzz” unless n % 3 ==0 if n % 5 == 0
puts “FizzBuzz” if n % 3 ==0 if n % 5 == 0
}

365. Mike Swierczek - December 7, 2007

I didn’t know a damn thing about computers when I got to college. I took a few simple CS courses as an undergrad. It’s senior year, I’m kicking around the idea of grad school, so I go for Software Engineering. I’m accepted (no GRE subject test required), and find out the program is about the Mythical Man Month, formal proofs that functions will exit, project management, Design Patterns, and so forth.

I think most of the people here were immersed in this culture, some at an early age. I didn’t even realize how many free compilers and online tutorials for different tasks and languages existed. I was a fish out of water, and I didn’t even know how to get back into the ocean.

I snared a first job on the strength of my grades and good high level discussion of concepts, and then proceeded to be an anchor on my team for a solid six months and then maybe just floating driftwood for six more. That was six years ago, and now FizzBuzz is quite easy.

I’m sure there are interviewees that are hoping to lie their way through the process. But there are also some people new to the field – some young, some not – that can be damn good developers if you give them some time. I’m not saying you should hire them, I’m just asking you to cut them some slack. Maybe encourage them to pick up some good books and work through the examples before they interview anywhere else.

366. sclv - December 18, 2007

swapping two variables, declaring *none*: uncurry (flip (,))

367. Bony - December 21, 2007

This is the greates article about Fizz-Buzz .

368. JavaGuy147 - December 29, 2007

the C way of swapping two variables without a temp var is very simple. For those who don’t know it:

a^=b^=a^=b;

you can also use adding/subtracting the variables in the right order but I don’t think the method is worth showing

369. rille111 - January 4, 2008

Just to show you lot how simple and nice VB.NET is, i can do this in 3 lines.

For i As Integer = 1 To 100 Step 1
Console.WriteLine(i & “: ” & IIf(i Mod 3 = 0, ” fizz”, “”) & IIf(i Mod 5 = 0, ” buzz”, “”))
Next

370. MT - January 6, 2008

# Fizzbuzz in ruby
def fizzes(i); i % 3 == 0; end
def buzzes(i); i % 5 == 0; end
def boring(i); not(fizzes(i) or buzzes(i)); end
(1..100).each do |i|
print “Fizz” if fizzes(i)
print “Buzz” if buzzes(i)
print i if boring(i)
puts
end

—-

# Reading numbers from file and totalling, may fail if file
# contains blank lines or non-numerics.
File.readlines(“numbers.txt”).collect { |line| line.chomp.to_i }.inject { |t, i| t+i }

—-

# Convert from number to string without using
# built-in converters like printf and variable interpolation.
# ?0 is the ASCII value 0, and the chr() method gives the
# string equivalent of the ASCII value.
n = 436
str = “”
while n>0
digit = n % 10
n = (n-digit) / 10
str = (?0 + digit).chr + str
end
puts str

—-

Not sure why I’m posting the result, except I enjoyed thinking about albeit simple little challenges like this; a welcome relief from the complexities of real projects. Besides, I enjoyed reading some of the other people’s replies.

Some people seem to be reading too much into the purpose of the OP’s test. If your programmer / developer can’t manage these simple algorithms then that is certainly useful information to reveal. How you weigh that in with rest of your presumably extensive interview information depends entirely on your goals and requirements. A useful little test if you ask me.

371. Krenzel.info » Blog Archive » FizzBuzz - January 7, 2008

[...] wrote a great post titled Why Can’t Programmers.. Program?. The author references another post by Imran which introduces what is now a commonly referenced programming “challenge” [...]

372. adrien - January 9, 2008

here is a c# one liner solution
for (int x = 1; x <= 100; x++) Console.WriteLine(x + “:” + (x % 3 == 0 ? “Fizz” : “”) + (x % 5 == 0 ? “Buzz” : “”));

373. waseem - January 9, 2008

#include

main(){
int n;
for(n=1;i<=100;n++){
if(n%3==0 && n%5==0)
printf(“FizzBuzz\n”);
else if(n%3==0)
printf(“Fizz\n”);
else if(n%5==0)
printf(“Buzz\n”);
else
printf(“%d\n”,n);

}//for

}//main

374. Rudolf - January 12, 2008

Ha, I asked a intern at my company yesterday, in 3 minutes he came up with this PHP piece.

for($i=1; $i < 101; $i++) {
echo ( $i % 15 ? $i % 3 ? $i % 5 ? $i : “Buzz” : “Fizz” : “FizzBuzz” ).”\n”;
}

375. McWow the busy - January 15, 2008

[...] 20x more productive than the guy in the 5- area. But then again, that 5- area is why we end up with FizzBuzz. 20x is even being generous to the guys at the bottom. I’d have no problem believing infinity [...]

376. Rich - January 17, 2008

A C#/LINQ centered attempt

using System;
using System.Linq;
using System.Collections.Generic;

public class FizzBuzzer
{
delegate string FizzBuzz(int i);

public List GetFizzBuzzList()
{
FizzBuzz r = delegate(int i) { return (i % 5 == 0 ? “Fizz” : “”) + (i % 3 == 0 ? “Buzz” : “”); };
var q = from f in Enumerable.Range(1, 100) select r(f);
return q.ToList();
}
}

//…
foreach(string s in new FizzBuzzer().GetFizzBuzzList())
{
Console.WriteLine(s);
}

377. Someguy - January 18, 2008

I am forced to wonder if Mitch Silverman, post #4, has been driving down dark country roads at 80 mph… Backwards?

“.. or did (s)he get that deer in the taillights look in his/her eyes?

378. robbat2 - January 27, 2008

90 seconds.

#include <stdio.h>
int main(int argc, char** argv) {
int i; for(i = 1; i<=100; i++) { if(printf(“%s%s”, (i % 3) ? “” : “Fizz”, (i % 5) ? “” : “Buzz”) < 4) printf(“%d”, i); printf(“\n”); } }

But shoot me for abusing the return value of printf.

379. RS - January 27, 2008

They’re teaching kids Java…. at least at the school I’m at, it’s all theory too, not actual practical programming. Great for students that want to become CS teachers, but bad if they want to work for an actual company.

90 seconds.

<?php
for ($i=1; $i

380. RS - January 27, 2008

$i++) {
if (($i % 3 == 0) && ($i % 5 == 0)) {
echo “FizzBuzz \n”;
} elseif ($i % 3 == 0) {
echo “Fizz \n”;
} elseif ($i % 5 == 0) {
echo “Buzz \n”;
} else {
echo “$i \n”;
}
}

381. Mikachu - January 27, 2008

there are a lot of comments, so maybe someone mentioned this already: you have to check if a==b in your xor swap functions or you will just clear both of them, as a^a == 0.

382. Aigarius - January 27, 2008

a = [0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz"]
for i in range(1,101):
print a[i%15] ? i, a[i%15]

383. Sael - January 29, 2008

I got hired in the summer ’07, and was put through three tests besides the usual talky-talky stuff for the interview.

One was writing a stored procedure in T-SQL.

Next, doing a bit of UML – heck, just pseudo-sketching the “basket”-part of a web shop did the trick actually.

And last, doing FizzBuzz in C#. I was asked first if I had ever heard of it before, which I truthfully answered no to. In essence, I wrote the code in hand (taking about 1,5 minute since it takes forever to write readable handwriting these days).

I was later told that although my solution was almost perfect (could’ve been more tightly written), I was chosen over other candidates because of the speed of solving it, as well as actually listening and chit-chatting while doing it. See, the company used it more as a test of a person’s ability to work in an abstract environment – talking about stuff while doing it at the same time was the real test.

Still, they told me that they threw candidates out as soon as they displayed a lack of abilities in any of the three tests (since they are so simple).

BTW, this was in Denmark, and my education which was completed in the Spring of ’07 isn’t in Computer Science as such, but more just a special education to become a “coding monkey” of sorts – that is, having a practical approach to code, instead of a theoretical as CS usually is over here.

384. Fizz, buzz, fizzbuzz | Libin Pan - February 7, 2008

[...] Imran On Tech: Using FizzBuzz to Find Developers who Grok Coding [...]

385. FizzBizz in JavaScript : minutiae - February 11, 2008

[...] About a year ago someone put up a blog post on using using FizzBizz to find developers who grok code. [...]

386. Flashtastic - February 12, 2008

FizzBuzz in ActionScript:

for (var i = 1; i<=100; i++) {
if ((i%5) == 0 && (i%3) == 0) {
trace(i+” FizzBuzz”);
continue;
} else if (i%5 == 0) {
trace(i+” Buzz”);
} else if (i%3 == 0) {
trace(i+” Fizz”);
} else {
trace(i);
}
}

387. joker - February 13, 2008

I know the answer
print(1);
print(2);
print(Fizz);
print(4);
print(Buzz);
print(Fizz);
print(7);
print(8);
print(Fizz);
print(Buzz);
print(11);
print(Fizz);
print(13);
print(14);
print(FizzBuzz);
print(16);
print(17);
print(Fizz);
print(19);
print(Buzz);
print(Fizz);
print(22);
print(23);
print(Fizz);

ok I am just too lazy to complete this joke.

388. james mckay dot net » Pro JavaScript Techniques - February 16, 2008

[...] Personally, I’ve felt a bit disappointed by this. I’ve said before that I think of JavaScript as the new Scheme — so with that in mind, anything that treats it as if it were merely client-side PHP will naturally be something of a disappointment. Perhaps this is a case of quidquid latine dictum sit, altum viditur on my part, but I like to use closures, lambdas, iterators, generics, Linq and so on in my code to maximum effect. I am also firmly of the opinion that every professional developer needs to be familiar with these concepts too — after all, they show that you have the kind of mind that can handle the complexities of software development, and won’t stumble over the FizzBuzz problem. [...]

389. How to talk about Data Structures : mcherm.com (beta) - February 17, 2008

[...] what I would consider the most fundamental of programming skills. Some people have suggested using FizzBuzz (a trivial programming exercise) as a filter; what I use is a discussion of data [...]

390. Missing Features » Are You An Efficient Programmer? - February 25, 2008

[...] Most programmers are really bad at programming. Grab 10 random students from a computer science masters program and your correspondent will happily wager a case of Brooklyn Brewery Chocolate Stout that at least nine of those programmers will fail a basic programming task. [...]

391. mdp - February 27, 2008

Hope this code renders properly.
Does the plaintext tag work?

I only just heard about FizzBuzz, and while there
are implicit sieves posted, there does not seem
to be an actual sieve.

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

#define SIEVE_SIZE 101

int main (void)
{
int retval = 0;
int idx;
int it;
char sieve[SIEVE_SIZE];
int fizz_mask = 0x01;
int buzz_mask = 0x02;

for(idx = 0; idx < SIEVE_SIZE; ++idx) sieve[idx] = 0;
for(idx = 0; idx < SIEVE_SIZE; idx += 3) sieve[idx] |= fizz_mask;
for(idx = 0; idx < SIEVE_SIZE; idx += 5) sieve[idx] |= buzz_mask;
for(idx = 1; idx < SIEVE_SIZE; ++idx)
{
if((it = sieve[idx]) == 0) printf(“%3d\n”, idx);
else
{
if((it & fizz_mask) == fizz_mask) fputs(“Fizz”, stdout);
if((it & buzz_mask) == buzz_mask) fputs(“Buzz”, stdout);
fputc(‘\n’, stdout);
}
}

return retval;
} /* main */

392. FizzBuzz To Infinity « Better Software. Better Science. Better Sense. - March 1, 2008

[...] in Software tagged fizzbuzz at 1:12 pm by mj If you’re like me, the first time you heard the FizzBuzz programming interview meme, you tried it yourself in your favorite [...]

393. Justin Blaauw - March 15, 2008

When I followed the link to FuzzBuzz it vaguely rang a bell. Then on reading the site, I remembered – I had to do this test as part of an interview process for a place called GuruHut in South Africa. I creamed it but was wondering why they would ask someone like me – a 7 year experienced Java developer to write this code. Now I understand : )

394. C40’s Blog » Ruby và thú vui “code 1 dòng” - March 26, 2008

[...] Bài này có thể gọi là “siêu dễ”. Thế nhưng mà phần lớn dân tốt nghiệp lập trình không giải được bài này (hô hô). [...]

395. Paul - March 27, 2008

I didn’t read all the posts but many solutions repeat the multiple test with the modulo operator. Why test i mod 3 then i mod 5 and also test i mod 3 AND i mod 5 again.
Why not just:

for (i = 1; i <= 100;i++)
{
mod3 = 0
mod5 = 0

if (i % 3 == 0)
{
mod3 = 1
print(“Fizz”)
}
if (i % 5 ==0)
{
mod5 = 1
print(“Buzz”)
}
if (!(mod3 || mod5))
print(i)
}

But one problem is that for sequences like 9,10, or 24,25, etc FizzBuzz is printed because 9 is a multiple of 3 and 10 is a multiple of 5. So FizzBuzz gets printed even though neither 9 or 10 are multiples of 3 AND 5. That would throw me on a interview test because it would make me think its a trick question and that the only time FizzBuzz should get printed is if a number is a multiple of 3 AND 5, not when there are consecutive numbers that are mutliples of 3 and 5 respectively that may also print FizzBuzz. The time spent looking for the trick or gotcha would take more than a minute, and I am kicked out as a bad programmer because it took longer than a minute to finish such a simple problem :(
There are no simple problems.
Paul

L. - January 11, 2012

Aside from your remarks (i.e. no new line is making it a bit strange), checking again for the mod is a crime in itself. you already know if it matches mod3 or mod5, so just use that knowledge instead of asking for another expensive (double) op.

396. joe - May 18, 2008

(define (fizzbuzz n)
(let ((test (cond ((= 0 (modulo n 15)) “Fizzbuzz”)
((= 0 (modulo n 5)) “Fizz”)
((= 0 (modulo n 3)) “Buzz”)
(else n))))
(if (= n 0) (list n)
(cons test (fizzbuzz (- n 1))))))

(map print (fizzbuzz 100))

397. Keber - June 2, 2008

Hi,

I gave this problem to my students of two programming’s first course . One group, with teacher’s help, answered it in about two hours, most of them making unnecessary comparisons. In the other group, without help, about 25% step out the question, and about 10~15% gave an acceptable answer.

398. Anonymous - June 15, 2008

var i=0;

while (i < 100) {
i++;
if (i%3==0 && i%5==0) {
fb=”Fizzbuzz”;
document.write(fb + “, “);
} else if (i%3==0) {
f=”Fizz”;
document.write(f + “, “);
} else if (i%5==0) {
b=”Buzz”;
document.write(b + “, “);
} else {
i=i;
document.write(i + “, “);
}
}

399. Anonymous - June 15, 2008

Written in Javascript, forgot to include that.

400. Interviews : Please Stop Yelling - June 16, 2008

[...] FizzBuzz. A small problem that someone used to in an interview to test a programmer’s skills. Using FizzBuzz to Find Developers who Grok Coding It’s worth reading the comments on this [...]

401. Eric - June 21, 2008

I stumbled on this thread while reading stuff on Ruby (trying to understand why it’s so “popular”). It’s so hard to read, i bet you lose any gain you could get from it’s supposed fast developpement abilities! ah! ah!;)

This post what interessing in that regard, to see a few exemple of different languages for the same very simple problem.

The solution someone posted in Basic (i havent check if it’s valid) was to me the best exemple of how someone should answer such question in a interview (on paper), “pseudo-code” style:

for i = 1 to 100
if i mod 3 = 0 then print “Fizz”
if i mod 5 = 0 then print “Buzz”
if i mod 3 > 0 and i mod 5 > 0 then print str$(i)
next

(the str$ is a bit horrible… but it’s still readable overall)

Reading some of the other samples, it’s no surprise so much of the developpers have to work at night to get their job done! :)

402. :l: / Obfuscated FizzBuzz - June 26, 2008

[...] I read the original fizzbuzz article, I have suggested it to a couple people as an interview question and it seems to do its job as a [...]

403. Eric - June 28, 2008

“:l: / Obfuscated FizzBuzz”

I’m not sure what you have understanded better than everyone else!

Just for the fun of it (the basic version of the other guy was bad):

This version in realbasic has around 189 tokens (wich include all the formatting characters for indentation (realbasic autoformat), scope correct variable declaration and also valid output (at least to what i understand — the description of the problem doesnt specify if the print had to be on a new line, the code could be shorter otherwise!). Even with a logical hack/optimisation, it’s still readable!

dim i as integer
for i = 1 to 100
dim t as string
if i mod 3 = 0 then t=t+”Fizz”
if i mod 5 =0 then t=t+”Buzz”
if t=”” then
t= str(i)
end if
print t
next

Still shorter than your obfuscated version (around 216 chars)…. :b

And in Macromedia lingo, from memory as i dont have the environnement:

repeat with i from 1 to 100
t=””
if i mod 3 = 0 then t=t&”Fizz”
if i mod 5 =0 then t=t&”Buzz”
if t=”” then
t= i
end if
put t
end repeat

404. Wang-Lo - July 10, 2008

That’s not a short program. THIS is a short program:

Digital Equipment Corporation PDP-8 FIZZBUZZ program:
118 12-bit words (equivalent to 177 modern 8-bit bytes)
ON THE BARE METAL INCLUDING THE DEVICE DRIVER!
These 118 words are the only ones that need to be in
the entire computer — no OS, no BIOS, nothing else.

And this is on a CPU that not only doesn’t have a FPP,
it doesn’t even have hardware multiply and divide.
In fact, it doesn’t even have a SUBTRACT instruction.

So don’t be telling me about your “short” 80-byte
scripts that can only live in a 256MB OS with a
runtime library the size of a two-car garage. Punks.

/ FIZZBUZZ PROGRAM COPYRIGHT 2008 WANG-LO

* 200 / STANDARD START LOC

/ ****** THE MAIN PROGRAM ******

CLA
TLS

DCA IVALUE / PRESET DISPLAY VALUE
CLA CLL CMA RTL / PREP MOD 3 SIEVE
DCA MOD3CT
TAD M5 / PREP MOD 5 SIEVE
DCA MOD5CT
TAD M100 / PRESET LOOP COUNTER
DCA LOOPCT

MAINLP, ISZ IVALUE / DISPLAY 1..100 NOT 0..99
ISZ MOD3CT
JMP NOTM3 / ITS PLAIN OR BUZZ
CLA CLL CMA RTL / ITS FIZZ OR FIZZBUZZ
DCA MOD3CT / RESET MOD 3 SIEVE
ISZ MOD5CT
JMP NOTM5 / ITS FIZZ
TAD M5 / ITS FIZZBUZZ
DCA MOD5CT / RESET MOD 5 SIEVE
JMS PRTEXT
106 / F
151 / i
172 / z
172 / z
142 / b
165 / u
172 / z
172 / z
0
JMP DONELP

NOTM5, JMS PRTEXT
106 / F
151 / i
172 / z
172 / z
0
JMP DONELP

NOTM3, ISZ MOD5CT
JMP NOTANY / ITS PLAIN
TAD M5 / ITS BUZZ
DCA MOD5CT / RESET MOD 5 SIEVE
102 / B
165 / u
172 / z
172 / z
0
JMP DONELP

NOTANY, TAD IVALUE
JMS PRNUMB

DONELP, JMS PRCRLF / ONE INERATION PER LINE
ISZ LOOPCT
JMP MAINLP
HLT / STOP
JMP .-1 / STOP MEANS DONT GO AGAIN

M100, 7634 / NUMBER OF LINES TO PRINT
M5, 7773

IVALUE, 0
MOD3CT, 0
MOD5CT, 0
LOOPCT, 0

/ ***** THE RUNTIME LIBRARY *****

/ PRINT A POSITIVE INTEGER (IN RANGE 0..4095)
PRNUMB, 0
DCA SVNUMB / SAVE VALUE TO BE PRINTED
DCA LZFLAG / CLEAR LEADING-ZERO FLAG
JMS PRDDGT / 1ST DGT IF NOT LEADING ZERO
6030 / -1000
JMS PRDDGT / 2ND DGT IF NOT LEADING ZERO
7634 / -100
JMS PRDDGT / 3RD DGT IF NOT LEADING ZERO
7766 / -10
TAD SVNUMB / 4TH DGT
TAD KA0
JMS PRCHAR
JMP I PRNUMB
PRDDGT, 0
DCA NUMBCT / CLEAR DIGIT VALUE
PRDGLP, TAD I PRDDGT / SUB DGT WGT FROM NUM VALUE
TAD SVNUMB
SPA
JMP PRDGEX / TOO FAR — GO PRINT
ISZ NUMBCT / COUNT WGT-SUBTRACTION
DCA SVNUMB / RESTORE DIMINISHED VALUE
JMP PRDGLP
PRDGEX, CLA / DISCARD OVERDIMINISHED VAL
TAD NUMBCT / EXAMINE WGT-SUBTR COUNT
SZA
JMP PRDGDO / NOT ZERO — PRINT IT AND SET FLAG
TAD LZFLAG / ZERO — FLAG SET?
SZA
JMP PRDRTN / NO, LEADING ZERO — DONT PRINT
PRDGDO, TAD KA0 / YES — PRINT IT
JMS PRCHAR
ISZ LZFLAG / SET LEADING-ZERO FLAG
PRDRTN, ISZ PRDDGT / EXIT @+1
JMP I PRDDGT
KA0, 60
SVNUMB, 0
LZFLAG, 0
NUMBCT, 0

/ PRINT A TEXT MESSAGE (IMMED Z-TERM 7BIT ASCII)
PRTEXT, 0
TAD I PRTEXT / GEXT NEXT TEXT LEXT
ISZ PRTEXT
SNA / TEXT MUST END WITH ZERO
JMP I PRTEXT / RETURN TO LOC AFTER TEXT
JMS PRCHAR
JMP PRTEXT+1

/ PRINT END OF LINE
PRCRLF, 0
TAD K15 / CR
JMS PRCHAR
TAD K12 / LF
JMS PRCHAR
JMP I PRCRLF
K15, 15
K12, 12

/ ****** PRINTER DEVICE DRIVER ******

PRCHAR, 0
PSF
JMP .-1
PLS
CLA / SOME LPT DONT CLR AC
JMP I PRCHAR

405. Eric - July 16, 2008

And how do you pull that during a one hour interview? :b

406. Colin Alston - August 7, 2008

Discrete logic plus listcomp in Python.

[ (i%3 or i%5) and (i%3 and (i%5 and i or 'Buzz') or 'Fizz') or 'Fizz-Buzz' for i in range(1,101)]

407. TXGruppi » Archive » Teste seus códigos de qualquer lugar - August 11, 2008

[...] this paste permanently”. O site também tem exemplos de “Hello World” e “Fizz-Buzz” em cada linguagem. Outra funcionalidade é a criação de uma página para projetos, a mais [...]

408. TheDude - September 8, 2008

Script Injection Alert!

409. JB - September 15, 2008

The next questions should be….

OK, now it’s tomorrow and the customer is changing the requirements…

Now change it so that you can add support for any foreign language translation of “Fizz”, “Buzz” or “FizzBuzz”. It should accept languages that are read right-to-left (Hebrew) or require double byte character sets (Chinese).

And be sure to write it so that the number doesn’t need to be 100 but needs to be a positive integer. Wait, the customer just changed this as we were talking, it needs to be prime. Wait…..change that requirement to be a prime that is inferred from a message sent by another system at random intervals…..

410. markus - September 15, 2008

@ 401. Eric

You talk crap, but your program would seem to print fizzbuzz fizz-buzz on 15. You lose the interview.

411. recursive - September 16, 2008

@ 410. markus

How are you getting that? It only prints one of each of “fizz” and “buzz” for 15.

412. Bill G - September 18, 2008

I couldn’t see vbscript version – so here goes from rusty memory:

Option Explicit

Dim i

For i = 1 to 100
If i Mod 15 = 0 Then
Response.Write “FizzBuzz”
Else
If i Mod 3 = 0 Then
Response.Write “Fizz”
ElseIf i Mod 5 = 0 Then
Response.Write “Buzz”
Else
Response.Write i
End If
End If
Next

Do I win a prize for the longest snippet?

413. Bill G - September 18, 2008

Snippet envy??

414. Why So Confused? « learning the art of programming - September 27, 2008

[...] its syntax and write non-trivial programs in a week. I need to learn to do simple things first like Fizzbuzz and then go for the smaller challenges in Project Euler and then onto bigger [...]

415. Mediocre-Ninja.blogSpot.com - October 17, 2008

#fizzbuzz.rb
a = nil, ‘fizz’, ‘buzz’, ‘fizzbuzz’
1.upto(100) { |a[0]| puts a[(a[0]%3 == 0 ? 1 : 0) + (a[0]%5 == 0 ? 2 : 0)] }

416. Arun Saha - October 27, 2008

I would do the following implementation. Its little lengthy than some other already posted, but it
– is eaxy to extend e.g. “Jazz” for multiples of 7
– does not use modulo operator, which “may” be expensive

void
fizzbuzz() {

unsigned int i, nextFizz = 3, nextBuzz = 5, situation;

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

situation = 2 * ( i == nextBuzz ) + ( i == nextFizz );

switch( situation ) {
case 3:
printf( “FizzBuzz\n” );
nextFizz += 3;
nextBuzz += 5;
break;

case 2:
printf( “Buzz\n” );
nextBuzz += 5;
break;

case 1:
printf( “Fizz\n” );
nextFizz += 3;
break;

case 0:
printf( “%u\n”, i );
break;
}
}
}

417. Erik - November 6, 2008

C
C FIZZBUZZ IN FORTRAN IV
C
IMPLICIT INTEGER (I-N)
DO I = 1, 100
IF (MOD(I,3).EQ.0) WRITE(1,10)
IF (MOD(I,5).EQ.0) WRITE(1,20)
IF ((MOD(I,3).NE.0).AND.(MOD(I,5).NE.0)) WRITE(1,30) I
WRITE(1,40)
CONTINUE
STOP
10 FORMAT(‘FIZZ’,Z)
20 FORMAT(‘BUZZ’,Z)
30 FORMAT(I3,Z)
40 FORMAT(”)
END

418. Eric - November 19, 2008

@410. markus

The code on 401 was not mine!

@403 is doing the job exactly like it should.

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

In fact, i even tested the algorithm in Actionscript:

var tString:String;

for (var i:Number=1;i <=100; i++)
{
tString=””;
if (i%3==0)tString=tString+”Fizz”;
if (i%5==0)tString=tString+”Buzz”;
if (tString==””) tString=String(i);

trace(tString);

}

The output being:

11
Fizz
13
14
FizzBuzz
16
17

So, YOU talk crap! Waiting for your code answer! ah! ah! :)

419. Ablog » FizzBuzz Improved - November 24, 2008

[...] I explain how and why we make prospective hires write code on a whiteboard. In a similar vein, Imran on Tech posts about making developers write FizzBuzz. Several of us read the article, got caught in the, “Huh? That doesn’t sound hard. Let [...]

420. Test Your Might! « Software Bloat - November 30, 2008

[...] than one language may be appropriate, they choose the most expressive language available. Consider The FizzBuzz Problem (a simple “weed-out” problem given to interview candidates) which has been stated [...]

421. practice « Dion’s Weblog - December 8, 2008

[...] Here’s the infamous FizzBuzz: [...]

422. Lithping Lambda - December 24, 2008

1. Mmm.. I did not see immediately how to do it in a roundabout and convoluted way while using some intricate programming techniques (that’s what this challenge was about, right?)

But finally I made it, I made it marginally more convoluted, like this: Code:

#!/usr/local/bin/newlisp

(for (x 1 100 1)
(or
(and (set ‘three (= 0 (% x 3))) (println “Fizz”))
(and (= 0 (% x 5)) (or
(and three (println “FizzBuzz”))
(println “Buzz”) ))
(println x)
)
)
(exit)

2. .. but then thought again. The true corporate solution would be this:
Code:

(println 1)
(println 2)
(println “Fizz”)
(println 4)
(println “Buzz”)
(println “Fizz”)
(println 7)

Note to the team leader: “please forward this code to a junior member of the team to complete typing”

Note to the manager: “I have submited perfectly working code which should meet all deadlines. The team will be working on the next version as time permits to improve satisfaction in case of customer requests for number of items other than one hundred”

3. OOP.
By the time work on the second version started, however, it was mandated that all code followed the Object Oriented Paradigm.
So, in accordance with the principle that objects reflect real life entities, the program now generates 100 “Child_player” objects, which are passed request_messages from the Game_Master object (the supervisor pattern?). Each of the objects’ reply to the Fizz-Buzz question is then collected and formatted centrally for dispatch to the expernal requesting entity.

..mmm working on it.

4. Just got an e-mail from the management.
Version 3 is supposed to be a network distributed solution. Each of the 100 children objects will be converted to a freely-flying persistent network agent, which maintain their internal state and are able to change their chairs so to say, while still engaged in the game. Results are to be sent to a company overseas branch and support integrity checking and strong encryption

Help!

5. FINALLY: A truly geeky solution.

.. but there was in this company in the farthest corner of the room where all programmers sat a tiny office, and it was occupied by an old grumpy unix geek, who was actually the company system administrator.
As his servers buzzed on for the third year without a single reboot and his monitoring scripts notified him of the problems about 15 minutes before they hit, he had all the time on his hands to play with his favourite geeky toys. And one of such toys was functional programming.

So in half the time it took the company testing department to discover that typo in the customer report which turned an innocuous phrase into a grossly indecent one (slashing the company revenues and resulting in a couple of lawsuits by enraged budgerigar owners, all luckily settled out of court), he produced his own truly functional solution to the Fizz-Buzz problem.

It ran like this: Quote:

The input stream (potentially infinite, but reduced to the first 100 numbers for the sake of testing) is processed lazily, i.e. one item at a time.
The program runs 2 lazy generators in two coroutines, one spits numbers which are consequtive multiples of 3, the other one bakes multiples of 5 (or any other given numbers). So, once the generator is appropriately kicked, a new member of the virtual “list” is generated, the next multiple to check against.

The main program therefore checks each input value from that (infinite) input stream for _equivalence_ with the current 3-list and 5-list members by ping-ponging to the coroutine.
Once the equivalence is found, the 3-list or 5-list generator(s) lazily produce a next number for comparison.

But, to speed things up and save on the coroutine invocation, the numbers from those lazy generators are of course memoized, thus cutting up the needed time and improving performance

Everyone marvelled at the sight of the sysadmin prog crunching Fizz-Buzzer player numbers in the gazillions and the generality of the solution allowing it not to slow down even if 312345912358 and 512309482093481209358340 were the needed as multiples, but no one understood a thing, and management turned it down as totally unmantainable.

The geek then sligtly changed some output parameters of his script and posted it on the Internet, where it became popular as a computer game called “Squash the Bill”.

Has anyone seen it recently? Could you post the source code here?

423. Timothy Andrew - December 29, 2008

Jacob,
You can swap two variables without a third variable.

(if the variables are a & b)

a = a+b
b = a-b
a = a-b

424. My journey, Part 2 « Tekkie - December 29, 2008

[...] as an aside, I was alarmed to read Imran’s article in 2007 about using FizzBuzz to interview programmers, because the problem he posed was so simple, yet he said ”most computer science graduates [...]

425. Derek Illchuk » The Venerable FizzBuzz Problem - December 30, 2008

[...] at Imran on Tech, they presented a problem which they say stumps many comp sci. graduates (although, I have yet to [...]

426. Riaan de Lange - December 31, 2008

using System;
using System.Collections.Generic;
using System.Text;

namespace FizzBuzzConsoleCS
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
bool fizzbuzz3 = false;
bool fizzbuzz5 = false;
bool fizzbuzz35 = false;

fizzbuzz3 = (i % 3 == 0);
fizzbuzz5 = (i % 5 == 0);
fizzbuzz35 = (i % 3 == 0) && (i % 5 == 0);

if (fizzbuzz35)
Console.WriteLine(“{0}\t: FizzBuzz”, i.ToString());
else
if (fizzbuzz3)
Console.WriteLine(“{0}\t: Fizz”, i.ToString());
else
if (fizzbuzz5)
Console.WriteLine(“{0}\t: Buzz”, i.ToString());
else
Console.WriteLine(i.ToString());
}
Console.ReadLine();
}
}
}

427. Samuli K - January 13, 2009

Me too! :-) 65 bytes in PHP:
for(;++$i<101;)echo($i%15?$i%5?$i%3?$i:”fizz”:”buzz”:”fizzbuzz”);

428. Samuli K - January 13, 2009

…and by exploiting PHP it can be done in 59 bytes :-)
for(;++$i<101;)echo($i%15?$i%5?$i%3?$i:fizz:buzz:fizzbuzz);

429. Fizz Buzz: Can You Do It? : Jesse Dearing.com - January 20, 2009

[...] am surprised to read that people cannot do Fizz Buzz in an interview[1][2][3]. As a test to myself I just wrote Fizz Buzz in SQL, which I don’t know very much SQL and I used [...]

430. cnb - January 22, 2009

plain english algorithm:
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”.

for each i from 1 to 100
if i is divisible by both 3 and 5 print fizzbuzz
else if i is divisible by 3 print fizz
else if i is divisible by 5 print buzz
else print i
end-for

431. Top 10 Questions to Ask Senior DBA job candidates | Brent Ozar - SQL Server DBA - January 22, 2009

[...] Here’s a quote of the FizzBuzz problem: [...]

432. Michael B - January 27, 2009

“@ Jacob I can do it without using a 3rd variable and in only 3 lines (your *How fast they do it* issue)

X=2, Y=5

x=x+y \* x=7 *\
y=x-y \* y=2 *\
x=x-y \* x=5 *\

x=5, y=2 (Hence done…)

But you would just turn me down if i presented you with this solution.

how the hell is the interviewee supposed you want him to use a 3rd variable if he knows a better way of doing it? He is supposed to read your mind?

Anyway, sorry for the disturbamce.”
now try it for X=Integer.Max and Y=1

As for the XOR solution:

http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice

(yes I had to look part of that up but I knew it didn’t work as would be expected) I suppose youu could defend against two equal values but hey..

tbh if I come across it in an interview I would either have a vote of miss-confidence or if I was the one who was being interviewed: would probably look on.

That line of though would also surfaces with FizzBuzz problem, though I could probably get over it by dismissing it as a root-out method. Just make sure you never pull it on anything but the first interview.

L. - January 11, 2012

Well .. you’re wrong like so many before you – and it was pointed out before you answered.

Should the variable not be a numeric type, you’d require double conversions … all that to avoid a third variable when you’re obviously not thinking much further than 4 bit integers..

I would be surprised if creating a third variable in registers was slower than doing three basic arithmetic ops … – in a general case of course, not counting corner cases like register is exactly 100% full with a and b or something -

433. Mechanical Engineering Vs. Software Engineering | iLude - January 28, 2009

[...] of plumbing a single family home. This type of plumbing is the  software development equivalent of FizzBuzz. Which is to say that it takes some skill and understanding to do it correctly but overall its not [...]

434. Random Thought Experiment - Swapping Variables « Random Code - February 2, 2009

[...] Filed under: General — Neal @ 8:40 am Recently I was reading a post about using a fizzbuzz test to find developers that grok coding.  Some of the comments also talked about using a simple swap test (i.e. swap the values of these [...]

435. FizzBuzz in T-SQL - February 3, 2009

[...] Dave posted yesterday about how to solve the Fizz Buzz problem using T-SQL. Definition of FizzBuzz Puzzle : Write a program that prints the numbers from 1 to 100. [...]

436. Dustin - February 9, 2009

FWIW, the XOR swap isn’t always the fastest on some systems… It is an old trick that was used for speed-crucial applications back in the ASM days. Most decent compilers can optimize to the fastest compiled solution for a specific target. However, it is a nice trick to know anyway. ^_^

I am actually surprised to see so many Python and Ruby solutions though. It’s nice to see! ^_^

437. bbizbor - February 17, 2009

Поставте антиспам

438. esteve - February 19, 2009

What did we learn recursion in the University for?

In the old good Pascal:

procedure fizzBuzz(min,max,mod3,mod5:integer);
begin
if (min>max) then EXIT;
if (mod3=0) then write(‘Fizz’);
if (mod5=0) then write(‘Buzz’);
if (mod3*mod50) then write(min);
fizzBuzz(min+1,max,(mod3+1) mod 3, (mod5+1) mod 5);
end;

you can call it fizzBuzz(1,100,1,1)

439. FizzBuzz for Speccy - February 26, 2009

For fun, there’s a ZX Spectrum BASIC version:

10 LET fizz = 0
20 LET buzz = 0
30 FOR i = 1 to 100
40 LET disp = 0
50 LET fizz = fizz + 1
60 LET buzz = buzz + 1
70 IF fizz = 3 THEN GO SUB 200
80 IF buzz = 5 THEN GO SUB 300
90 IF disp = 0 THEN PRINT i
100 IF disp = 1 THEN PRINT “Fizz”
110 IF disp = 2 THEN PRINT “Buzz”
120 IF disp = 3 THEN PRINT “FizzBuzz”
130 NEXT i
140 STOP
200 LET fizz = 0
210 LET disp = disp + 1
220 RETURN
300 LET fizz = 0
310 LET disp = disp + 2
320 RETURN

… and the exact implementation in ZX Spectrum ASM (BIN is only 105 Bytes!?):

; For the loader:
; 10 CLEAR 32768
; 20 LOAD “” CODE
; 30 RANDOMIZE USR 32768

org $8000 ; 32768

start

; B = Loop
; C = Number in 2 digits
; D = Fizz
; E = Buzz
XOR A
LD C, A
LD D, A
LD E, A
LD B, 100
loop:
; Increment C and adjust decimal
LD A, C
ADD A, #1
DAA
LD C, A
; Increment Fizz & Buzz
INC D
INC E
; Reset H (for output select)
LD H, 0
; Check if Fizz go over 3
LD A, D
CMP 3
JR NZ, skipfizz
SET 0, H ; H = H | 1
LD D, 0
skipfizz:
; Check if Buzz go over 5
LD A, E
CMP 5
JR NZ, skipbuzz
SET 1, H ; H = H | 2
LD E, 0
skipbuzz:
; Display the text
LD A, H
CMP 0
JR Z, printnum
BIT 0, H
CALL NZ, printfizz
BIT 1, H
CALL NZ, printbuzz
enddisplay:
LD A, $0D ; Enter Key
RST 16
DJNZ loop
RET
;
; Print “Fizz”
printfizz:
LD A, $46 ; F
RST 16
LD A, $69 ; i
RST 16
LD A, $7A ; z
RST 16
LD A, $7A ; z
RST 16
RET
; Print “Buzz”
printbuzz:
LD A, $42 ; B
RST 16
LD A, $75 ; u
RST 16
LD A, $7A ; z
RST 16
LD A, $7A ; z
RST 16
RET
; Print number in register C as 2 digits
printnum:
LD A, C
AND $F0
SRL A
SRL A
SRL A
SRL A
JR Z, skipd2zero
ADD A, $30
RST 16
skipd2zero:
LD A, C
AND $0F
ADD A, $30
RST 16
JR enddisplay

end start

440. Upendra - March 5, 2009

In clasicc VB (VB6):

For i=1 to 100
If i Mod 3=0 and i mod 5 =0 then
debug.print “FizzBuzz”
elseif i Mod 3 = 0 then
debug.print “Fizz”
elseif i Mod 5 =0 then
debug.Print “Buzz”
else
debug.Print i
end if
Next i

441. daveb78 - March 27, 2009

Oracle SQL:

select coalesce(
decode(mod(0+rownum,3) + mod(0+rownum,5),0,’fizzbuzz’,null),
decode(mod(0+rownum,3),0,’fizz’,null),
decode(mod(0+rownum,5),0,’buzz’,null),
to_char(0+rownum))
from dual connect by 0+rownum <= 100;

eskous - September 10, 2010

How about these?

Oracle SQL:

— The best?
SELECT NVL(DECODE(MOD(ROWNUM,3),0,’Fizz’)||DECODE(MOD(ROWNUM,5),0,’Buzz’),ROWNUM) FROM DUAL CONNECT BY ROWNUM<101;

— As short as the previous one.
SELECT NVL(SUBSTR('Fizz',5*MOD(ROWNUM,3))||SUBSTR('Buzz',5*MOD(ROWNUM,5)),ROWNUM) FROM DUAL CONNECT BY ROWNUM<101;

— A clear idea.
SELECT DECODE(INSTR(MOD(ROWNUM,3),0)||INSTR(MOD(ROWNUM,5),0),1,'Buzz',10,'Fizz',11,'FizzBuzz',ROWNUM) FROM DUAL CONNECT BY ROWNUM<101;

— An obscure idea.
SELECT DECODE(MOD(MOD(ABS(4*MOD(ROWNUM,15)-30),9),6),0,'Fizz',1,'Buzz',3,'FizzBuzz',ROWNUM) FROM DUAL CONNECT BY ROWNUM<101;

442. gork - March 27, 2009

doods
it’s simple math
simple math
with simple probelm solving abilities

why is everyone hung up on this shit with tweaking the most functionality out of the smallest amount of code?

you all remind me of the guitar masturbators who listen to led zep and jimi hendrix over and over again and talk about it all the freaking time

hell
i got into computer programming to use the computer as a tool to solve problems and make money….

did you get into it so you could memorize the latest ROR shit?

if i interviewed half of you i would tell you to fuck off
i want to know if you can SOLVE the problem
not interested in your single minded ability to code in language X

these tests are for stupid dumb asses who need some sort
of measure of ability to think – geez sounds like a god damn IQ test

443. Anonymoose - March 27, 2009

You got that right, G0rk not like probelm [sic]. And no, G0rk not show hairdo, either.

G0rk do just fine teach self Visalu Basic in 21 Day, k-thx-bye.

444. Anonymoose - March 27, 2009

Oops. Srry about typo. G0rk Mean Visula C+ in 21 Day.

445. a - March 27, 2009

ug, me gork. me no like programming test. makes brain hurt.

446. jkua - March 27, 2009

MATLAB!

i = (1:100)';
div1 = 3;
div2 = 5;
string1 = ‘Fizz';
string2 = ‘Buzz';

str1len = length(string1);
str2len = length(string2);
maxNumLen = length(int2str(i(end)));
output = repmat(‘ ‘, size(i, 1), max(str1len + str2len, maxNumLen));

mod1 = mod(i, div1) == 0;
mod2 = mod(i, div2) == 0;
output(:,1:maxNumLen) = num2str(i, ‘%d’);
output(mod1,1:str1len) = repmat(string1, sum(mod1), 1);
output(mod2,1:str2len) = repmat(string2, sum(mod2), 1);
output(mod1 & mod2,1:str1len + str2len) = repmat([string1 string2], sum(mod1 & mod2), 1);
disp(output);

447. OakdaleFTL - March 28, 2009

…I admit, I didn’t read all of these comments: But isn’t it a little scary, how many posters were unaware of how the commenting system would parse their code?

L. - January 11, 2012

Well .. If I had to choose between someone who knows htmlspecialchars by heart, and someone who knows how to code .. it’d be damn quick.

While from a web standpoint (and yes the future is going to be full of webapps – that need a real backend not in PHP though) it looks ridiculous that someone would not realize &gt was the culprit (see what I did there ;) ) – it’s just webdev knowledge.

So yeah . might look like total fail but that doesn’t mean thing when you’re looking for a real coder and not just a php-drone.

448. Gary - March 28, 2009

Ok, here is my solution for Excel:
Populate cell A1 with the value 1
Populate the cell B1 with the following formula:
=IF(MOD(A1,15)<>0,IF(MOD(A1,5)<>0,IF(MOD(A1,3)<>0,A1,”Fizz”),”Buzz”),”FizzBuzz”)
Drag fill cells A1 and B1 down to row 100.

449. Brien Malone - March 30, 2009

Just for laughs… ColdFusion

#fbout#

450. Brien Malone - March 30, 2009

OakdaleFTL — most commenting systems are smart enough to parse it for you, offer code blocks or at the very least a preview. Oh well… here’s my second post.

<cfloop from=”1″ to=”100″ index=”fbidx”>
<cfset fbout=””>
<cfif fbidx mod 3 eq 0><cfset fbout=”fizz”></cfif>
<cfif fbidx mod 5 eq 0><cfset fbout=”#fbout#buzz”></cfif>
<cfif fbout eq “”><cfset fbout=fbidx></cfif>
<cfoutput>#fbout#</cfoutput>
</cfloop>

451. Celandro - April 1, 2009

450 posts and not a single good generic implementation? Written in 10 minutes and handles future requests from your pointy haired boss

import java.util.LinkedHashMap;
import java.util.Map;

public class FizzBuzz {
Map moduloStringMap;
int start;
int end;
public FizzBuzz (Map moduloStringMap, int start, int end){
this.moduloStringMap = moduloStringMap;
this.start = start;
this.end = end;
}
public String getModuloString(int num) {
String retval = “”;
for (Map.Entry e:moduloStringMap.entrySet()) {
if (num%e.getKey() == 0) {
retval += e.getValue();
}
}
if (retval.length()== 0) {
retval = Integer.toString(num);
}
return retval;
}
public void printAll() {
for (int i=start; i<=end; i++) {
System.out.println(getModuloString(i));
}
}
public static void main (String[] args) {
Map moduloStringMap = new LinkedHashMap();
moduloStringMap.put(3,”Fizz”);
moduloStringMap.put(5,”Buzz”);

FizzBuzz buzzKill = new FizzBuzz(moduloStringMap,1,100);
buzzKill.printAll();

}

}

452. Notatnik zapisywany wieczorami - April 6, 2009

Bajka o programującym durniu…

W Krainie Szczęśliwych Projektów wróżka Marketingalia szepce
menedżerom do ucha bajkę o cudownych narzędziach. O IDE, frameworkach,
generatorach aplikacji albo językach programowania, które pozwolą byle
durniowi sprawnie pisać formatki, raporty czy ekr…

453. Christopher Oliver - April 15, 2009

int main(int argc, char *argv[]) {
int n;
char *fb[] = {“%d\n”, “%d Fizz\n”, “%d Buzz\n”, “%d FizzBuzz\n”};

for (n = 1; n <= 100; n++) {
printf(fb[(n % 3 == 0) + 2 * (n % 5 == 0)], n);
}
}

454. Christopher Oliver - April 15, 2009

Rats. Forgot the error code. Imagine I wrote “return 0;” as the last statement of the outer block. [growl!]

455. just me - April 17, 2009

CREATE Table tblInt( anInteger int)
insert into tblInt values (0)
insert into tblInt values (1)
insert into tblInt values (2)
insert into tblInt values (3)
insert into tblInt values (4)
insert into tblInt values (5)
insert into tblInt values (6)
insert into tblInt values (7)
insert into tblInt values (8)
insert into tblInt values (9)

Select
“result” =
CASE
WHEN (ones.anInteger
+ (tens.anInteger*10) + 1)%15 = 0 THEN ‘FizzBuzz’
WHEN (ones.anInteger
+ (tens.anInteger*10) + 1)%3 = 0 THEN ‘Fizz’
WHEN (ones.anInteger
+ (tens.anInteger*10) + 1)%5 = 0 THEN ‘Buzz’
ELSE CONVERT(VARCHAR(10),(ones.anInteger
+ (tens.anInteger*10) + 1))
END
from tblInt as ones
CROSS JOIN tblInt as tens
order by ones.anInteger
+ (tens.anInteger*10)

DROP TABLE tblInt

456. Getting an education in America « Tekkie - April 26, 2009

[...] started hearing accounts of CS graduates who can (not) (program). Around the same time I was hearing complaints from universities about the inadequate [...]

457. Christopher Oliver - April 28, 2009

Actually, my problem seems to be not reading the instructions. Bah!
Once more with feeling:

int main(int argc, char *argv[]) {
int n;
char *fb[] = {”%d\n”, “Fizz\n”, “Buzz\n”, “FizzBuzz\n”};

for (n = 1; n <= 100; n++) {
printf(fb[(n % 3 == 0) + 2 * (n % 5 == 0)], n);
}
return 0;
}

458. Brad Mason - April 30, 2009

This can all be done in 1 query.

SELECT TOP 100
CASE
WHEN (ROW_NUMBER() over(order by c.object_id) % 15) = 0
THEN ‘fizzbuzz’
WHEN ROW_NUMBER() over(order by c.object_id) % 3 = 0
THEN ‘fizz’
WHEN ROW_NUMBER() over(order by c.object_id) % 5 = 0
THEN ‘buzz’
ELSE cast(ROW_NUMBER() over(order by c.object_id) as varchar(100))
END
FROM sys.objects o cross join sys.columns c

459. The Fizzbuzz problem « Harder, Better, Faster, Stronger - May 12, 2009

[...] a lot of programmers can’t get it right in a very few minutes. In fact, that’s what Imran claims. Quoting from his blog: Want to know something scary ? – the majority of comp sci [...]

460. David Welford-Costelloe - May 17, 2009

Well I don’t agree with this test, having a developer write on paper is not the solution. Developers (the good ones) work on the keyboard. To test math skills does not weed out the good from the bad. I once interviewed someone who could write amazing things on paper, put them into an IDE and they were lost. There are the memorizers as a call them… they can spill out every definition for a language. I have been developing for 16 years and I refuse to take these stupid tests that are snippets from Microsoft certification exams. If you read my resume and see the amount of experience I have don’t insult me with ‘what is a sql join’ or what is a variable. My rule is: I don’t take written tests if I want to be a writer I’ll study to be one.

I asked as part of the interview to bring in a sample application nothing fancy a simple application to input and output text. I look at the source and that is it. If it doesn’t build end of interview.

One question I ask is:
“You are stuck on a method, what help options do you use?”

:-)

461. Frustrated. - May 28, 2009

I have to agree that the majority of people in this day and age (at least in the lower to mid echelons) aren’t hired because they are geniuses in a field, but because they know where to go to seek assistance. I’d say more points should be awarded to knowing when they need to ask for help (or Google it). I’d rather have an engineer who knows his limits than one who thinks they know it all.

To reply to an earlier comment (George – February 2, 2007), “how to tell if you’re a bad programmer” –

Quote:
* Extra points if you avoid this by pretenting to do “design” before coding, and you just produce tons of documents and UML diagrams without ever touching the keyboard and leaving the dirty work of implementing your designs to other people.

* You do programming for money; doing it as a hobby (for fun!) is something that only madmen do.

I have to say, this is a prime example of the IT world’s complete departure from well-formed English. People “do” programming or design as much as someone “architects” a solution. This is a continuation of the complete butchery of the language. You either are a programmer or you aren’t. You don’t “do” it nor does one “do” design. You either are an architect or you aren’t, you don’t “do” it, and you don’t “architect” anything. There is architecture, and architectural, but it’s not a verb.

My point is that if you’re going to start bashing down the lesser competent people in your industry, rather than lending assistance or providing training opportunities to help bring them up to your standards (gasp!), first demonstrate basic mastery of the language you’re bashing them in. You look quite silly otherwise.

( / rant )

462. buzzyteam - May 29, 2009
463. wagied davids - June 27, 2009

Hi All,

Interesting posts. I have come across this phenomenon in academia and industry. However, it seems to be worse in academia!…hahaha.
My previous post-doctoral supervisor hailing from Yale working in Toronto, could not write code to save his life. We are in the field of computational biology.

I have seen educated people stare at computer screens similar to writers stare at blank pages. However, I would not call this a case of “writers-block”…but simple inexperience at a practical implementation of theoretical principles.

I have met very few people in my career that are all good-rounders ..they handle the math, the algorithms, the design and coding, as well as the artistic side of visual design. In academia, I have not met any.

In industry, the tempo ..is alot more fast paced, and your job is at risk. The incentive to get things done is a good motivation. In academia I have seen educated people sitting on projects for more than 6-9 months for a 3 month project, and I am not reffering to graduates with BSc, but MSc and PhDs in both countries that I have lived and worked (Canada and Sweden).

Possessing a large body of theoretical knowledge, however does not make a good programmer. Too much of their time is spent analyzing and predicting a result, when a computer can do the work in a few seconds to get a result.

What people in industry are looking for is a good combination of skills ranging from theoretical knowledge and practical skills but also multi-tasking abilities.

In some sense, a juggler who “thinks on his/her” feet while juggling balls. Those are the ones that are very few.

464. Michael - June 28, 2009

George, your Forth version is horrible and you’re making the rest of us Forthwrights look bad.

: fizz ( n — ? ) 3 MOD IF FALSE EXIT THEN TRUE .” Fizz” ;
: buzz ( n — ? ) 5 MOD IF FALSE EXIT THEN TRUE .” Buzz” ;
: bazz ( n ? — ) IF DROP EXIT THEN . ;
: fizzBuzz ( n — ) CR DUP fizz OVER buzz OR bazz ;
: fizzBuzzes ( n — ) 1+ 1 DO I fizzBuzz LOOP ;

100 fizzBuzzes

465. Dexter Garvey - July 4, 2009

We have an application under development for the iPhone designed to answer silly questions just like this for job hunters.

The best hire isn’t always someone who can pull answers like this out of thin air, more likely it’s someone who can find and understand an appropriate answer found on Google.

WTF re-invent the wheel?

466. :l: - July 9, 2009

@403
I “understanded” it just fine. The point of the question was to weed out people who can’t program, I think all the people doing naive implementations are only proving that they can get past a simple phone-screen question. I did the obfuscated version “just for fun” because a naive answer is trivial to the point of not being worth doing. A simple perl implementation is shorter than the obfuscated one. I was playing perl-obfuscation, not perl-golf.

@465
This is not a “pull out of the air” question. If you can’t loop or figure out when something divides by 3 or 5 you should be in an entirely different industry, an iPhone app wont give you competence. If I were interviewing someone and they said they needed to check the internet to figure it out they would not get past me.

My original comment was:


2 Things strike me about the article and a few of the more common references to it:

1) The commenter’s usually try to implement it.
2) The commenter’s usually try to implement it in visual basic.

I think both miss the point.

Here’s my attempt in perl. I think it would convince a lot of people _not_ to hire me if I gave it as a code sample. Can anyone get it down to 140 charactes (SMS) size? Seems like it should be possible with a few more shortcuts.

@c=(0,4,7,19,24);@e=(4,4);push@b,0,3,@e;push@f,1,2,@e;push@fb,@f,@b;sub x{$_+66};sub z{map(chr,map(x,map($c[$_],@_)))}sub b{z@b}sub f{z@f}sub fb{z@fb}sub p{print@_}for $i(0..shift){$i%15?$i%5?$i%3?p $i:p f:p b:p fb}

(put it in a file called script.pl, run it as ‘/usr/bin/perl -l script.pl 100′

The point was not that this is a programming exercise, the point is to see if the candidate even has a pulse.

467. T - July 17, 2009

wow lots of so smart people out there ;)

To the python and Perl guys who can swap variables without a third one:
What do you think the compiler is doing under the hood when it encounters something like: ($a, $b) = ($b, $a) ?
It will most likely implement a swap algorithm using a third variable. Also the inquiry was about the algorithm used and not a language specific shortcut.

Also these questions are not designed to find out, what a smart ass you can be, but if you can come up with a simple solution for a simple problem.

As for the guys thinking, that they need to provide solutions to the Fizz Buzz problem:
You are almost as pathetic, as the ones that couldn’t do it since you treat it like it is a challenge (which it isn’t).

Sorry if this is too harsh, but seeing makes me sick to my stomach.

468. stranger - July 29, 2009

in c without using modulo

void fizzbuzz(){
for (int i=1,j=0,k=0;i<101;j=i-j-3?j:printf("Fizz")+j-1,k=i-k-5?k:printf("Buzz")+k+1,i=i+(!(i-j)||!(i-k)?printf("\n"):printf("%-2d\n",i)-2));
}

469. Interview coding tests should measure more | IT Security | TechRepublic.com - August 20, 2009

[...] answerable questions. A popular subject of debate on the Internet a couple years ago was the FizzBuzz challenge, used to weed out the absolute worst coders applying for a job. Reginald Braithwaite [...]

470. Johnny - August 21, 2009

Of course, it’s always those “other programmers” who could not code even if their life depended on it. If I had a dime for every time I heard a programmer criticise another programmer’s code, while acting all superior and knowledgeable, I’d be a millionaire ;-)

Sometimes I wonder if people who are quick to label other programmers as weak are projecting some of their own insecurities onto those “weak programmers”. Perhaps those high school years have not been too kind to most of us nerds, so there’s this obsessive need to prove ourselves over and over, even if it just means putting others down.

I wish programmers were more collaborative and less competitive. I mean, this isn’t Math Olympics for 12-year-olds anymore. Or, is it?
It’s amazing how many “turf protectors” I’ve run into in the field of programming/software engineering. I mean, I am the first one to admit there’s a ton of stuff I don’t know, so why is it that some people feel the need to excessively brag and cover their knowledge gaps? It may sound harsh , but, sometimes I feel that programming attracts too many people with Narcissistic Personality Disorder.

471. Glorf IT - Bedenkliches aus dem IT-Alltag » Bewerbern auf den Zahn fühlen - August 24, 2009

[...] Bewerbern auf den Zahn fühlen :Von Thomas: Mein Kollege Peter machte mich auf einen Tests für Bewerber aufmerksam. Man solle Ihnen eine leichte Programmmieraufgabe geben, um die Fähigkeiten des Kandidaten zu erleben. Als Beispiel soll ein Programm die Zahlen von 1 bis 100 ausgeben. Ist die Zahl hingegen durch 3 teilbar, dann statt dessen "Fizz". Ist sie durch 5 teilbar, dann "Buzz". Ist sie aber durch 3 und 5 teilbar, dann "FizzBuzz". Erstmals beschrieben wurde das offenbar im Artikel "Using FizzBuzz to Find Developers who Grok Coding". [...]

472. ryba4 - August 31, 2009

If you want to show off your geekness, here’s some python code:

‘, ‘.join([['{0}', 'Fizz', 'Buzz', 'FizzBuzz'][(i % 5 == 0) + (i % 3 == 0) * 2].format(i) for i in xrange(100)])

473. The Content Wrangler » Blog Archive » Usability, Mobile Devices, and the Future of Higher Education: Interview with Robby Slaughter - September 6, 2009

[...] designers who have never heard of kerning or affordances, self-professed programmers who can’t code Fuzz-Buzz, methodological “experts” who can neither define sampling nor detect bias, technical writers [...]

474. Don s - September 8, 2009

I just went through a FizzBuzz test of a kind. They wanted a creative programmer who could whip up & describe a quick architecture on a whiteboard and explain it, so they set me out a problem and had me do just that – in real time, right there. Rough but serviceable.

They also wanted someone who knew his way around an agile environment and how and why. I took it to the whiteboard and diagrammed an xP/agile workflow for them.

Started yesterday, nuff said.

475. Douglas - September 9, 2009

I think that most of your posts and comments on what does a programmer should be able to do are quite wrong because the way nowadays development is carried out, it is completely away from the things like hexadecimal and some based-maths things that you have been talking about.

I think for example, that having knowledge about what base-16 hex is, can be important but not necessarily reflects what nowadays a developer should be able to know.
I think in these modern days, developers should be able to understand things like:
• what is a loop, how to manage things within a loop and what is to avoid within a loop?
• What is pessimistic development approach?
• What is a class?
• What is an object?
• What is an interface?
• Interface’s purpose?
• What is composition?
• What is a Service?
• What is a composite application?
• What are design patterns?
• Differences between script programming and non script programming languages?
• What loose coupling or reducing coupling means?
• What is abstraction?
• How to abstract software component services?
• What is MVC?
• What is a DAO?
• Good knowledge of SQL
• What is a web-container?
• How to provide unit test to your software solution
• What is an Object Factory?
• What is “the so overused” singleton pattern?
• What is integrity of the data?
• What is consistency?
• What is reliability?
• What is portability?
• How to provide flexibility?
• What is a transaction?
• What is a transactional application?
• What is a transaction manager?
• What is ORM?

I could continue listing things that we all should know today, but I am sure you have understood my point.
I mean, there are so many more important topics today to take care about than hexadecimal and other things I’ve read.

Of course, first of all a programmer should be able to provide high quality to their flow of controls and loops too.

This is my view of today programming and I can assure you that if you don’t understand properly the above listed topics, you won’t be able to get a good job.

Many thanks

476. eggspencer - September 17, 2009

for(i=1;i<101;i++){b=i%5;console.log(i%3?b?i:"Buzz":b?"Fizz":"FizzBuzz")}

477. JavaScript FizzBuzz in a tweet : Ed Spencer - September 17, 2009

[...] FizzBuzz challenge has been around a while but I stumbled across it again after reading another unique Giles [...]

478. name - September 18, 2009

It’s stupid to expect an experienced programmer to write any code on a paper without mistakes. It’s stupid because everybody is lazy to remember all the syntax, order of the arguments, full names of functions. Programmer almost always do not remember some auto-completable parts (parentheses, includes, long function names, quotes or apostrophes). It’s usually test which would completely discard skilled effective senior programmers and reward a complete newbie who will write the code in M$ Notepad and won’t be even able to compile it.

479. name - September 18, 2009

#include
#include

int main(void)
{
int i;

for (i = 1; i < 101; i++) {
if (!(i % 3 || i % 5))
printf("%d\n", i);
else if (i % 3 && i % 5)
puts("FizzBuzz");
else if (i % 3)
puts("Fizz");
else if (i % 5)
puts("Buzz");
}

return EXIT_SUCCESS;
}

480. name - September 18, 2009

int main(void)
{
int i;

for (i = 1; i < 101; i++) {
if (!(i % 3 || i % 5))
printf("%d", i);
else {
if (i % 3)
fputs("Fizz", stdout);

if (i % 5)
fputs("Buzz", stdout);
}
}

return EXIT_SUCCESS;
}

481. Fred - September 28, 2009

#include <stdio.h>

int main(int argc, char **argv){

int i;
for(i=1; i<=100; i++){
if (i%3 == 0) {
if (i%5 == 0) {
printf(“FizzBuzz\n”);
}
printf(“Fizz\n”);
}
else if (i%5 == 0) {
printf(“Buzz\n”);
}
else {
printf(“%d\n”,i);
}
}
return 0;
}

482. Vince O'Sullivan - October 2, 2009

Judging by the replies to this article, 199 out of 200 respondents can’t read!

It’s not about the answer. It’s about the ability to answer. Nothing more.

483. nofxx - October 3, 2009

It should be burried in the middle, but the var swapin’ in Ruby don’t need the 3rd var:

a, b = b, a

484. Shashi Gowda - October 3, 2009

Shortest Possible FizzBuzz (I think)

// C
main () {
int i;
for(i=1;i<=100;i++)
printf ("%d\r%s%s\n", i, i%3==0?"Fizz":"",i%5==0?"Buzz":"");
}

# ruby
(1..100).each {|i| puts "#{i}\r"+(i%3==0?'Fizz':'')+(i%5==0?'Buzz':'') }

// php
<?php
for($i=1;$i

@Vince O’Sullivan
Elegance’s got to count for something =)

485. jon - October 5, 2009

I’ll throw in my factor solution just for the fun :)

: print-FIZZ-BUZZ ( q — )
{
{ [ dup 15 rem zero? ] [ drop "FIZZ-BUZZ" print ] }
{ [ dup 5 rem zero? ] [ drop "FIZZ" print ] }
{ [ dup 3 rem zero? ] [ drop "BUZZ" print ] }
[ . ]
} cond
;

100 [1,b] [ myprint ] each

jon - October 5, 2009

sry, “myprint” reads “print-FIZZ-BUZZ”, of course

486. Enc - October 14, 2009

66 Characters in PHP.
while(++$i%101)echo$i%3?($i%5?$i:’Buzz’):($i%5?’Fizz':’FizzBuzz’);

Indented it looks like this:
while (++$i%101)
echo $i%3? ($i%5?$i:’Buzz’) : ($i%5?’Fizz':’FizzBuzz’);

487. Enc - October 15, 2009

63 Characters in PHP!

while(++$i%101)echo$i%15?$i%5?$i%3?$i:’Fuzz':’Buzz':’FizzBuzz';

488. Enc - October 15, 2009

57 Characters in PHP!

while(++$i%101)echo$i%15?$i%5?$i%3?$i:Fuzz:Buzz:FizzBuzz;

489. Enc - October 15, 2009

I should actually print Fizz, not Fuzz… still 57 characters :P

while(++$i%101)echo$i%15?$i%5?$i%3?$i:Fizz:Buzz:FizzBuzz;

490. Gabe - October 15, 2009

print map{($_%3?””:Fizz).($_%5?””:Buzz)||$_}(1..100)

52 Chars in perl. I give myself a B+ for lack of readability and over-geekiness.

I don’t ask FizzBuzz like questions right-off-the-bat in in-person interviews. I have learned over the years that nervousness can be an overwhelming consideration when interviewing. I ask only super-basic questions most of the time, escalate if the person is relaxed, and supplement with on-line examination which is less intimidating and more like real-life stress. This procedure seems much more reliable than bludgeoning intimidated candidates.

491. FizzBuzz in Practice « caines.ca/blog - October 28, 2009

[...] work we've been doing a bunch of technical interviews for new hires, and I thought I'd give the Fizzbuzz test a go for evaluating candidates.  I realize that it's a famous interview test, but in practice none [...]

492. andrey the giant - November 1, 2009

C with bit fiddling (embedded-type optimizations):
#include
int main(void) {
int i, j;
for (i=1;1<101;i++) {
j=0;
if (!(i%3))j|=1;
if (!(i%5))j|=2;
printf("%s%s\n", (i&1)?"fizz":"",(i&2)?"buzz":"");
}
return 0;
}

493. Bryan Ross - November 3, 2009

This took me a few minutes, with the first couple minutes spent over-analyzing the problem rather than just writing the most straightforward and easiest to understand implementation I could think of:

(In C)

#include 

int main(int argc,char* argv[])
{
	int i;
	for(i=1;i<=100;++i)
	{
		if(i % 3 == 0 || i % 5 == 0)
		{
			if(i % 3 == 0)
				printf("Fizz");
			if(i % 5 == 0)
				printf("Buzz");
			printf("\n");
		}
		else
			printf("%i\n",i);
	}
}
markc86 - March 11, 2010

I was also trying to be over-efficient. I saw post #6 and realized it.

It seems to me the first IF is redundant (in your code). The problem with removing it is where to put PRINTF(“\n”)? Maybe one could use the choice operator, but it still amounts to about the same amount of decisions.

Gerry - March 11, 2010

Both #6 and this make the mistake of repeating calculations instead of storing the values of “i % 3 == 0″ and “i % 5 == 0″ as booleans. Doing this would also help documentation and mean the calculations would only need to be changed in a single place if they ever needed changing. Repeating calculations in this instance won’t amount to much of a difference, but if you make that mistake here then you’re going to make it in other situations where the penalty is much greater.

Smiley - March 17, 2010

Thanks, Gerry!

494. Edgar Klerks - November 11, 2009

Oh wel why not post another haskell solution:

mod3 :: Integer -> Integer
mod3 = (flip mod) 3
mod5 :: Integer -> Integer
mod5 = (flip mod) 5
mod15 :: Integer -> Integer
mod15 = (flip mod) 15

— z is accumulation element
fizzBuzz’ :: Integer -> [String] -> [String]
fizzBuzz’ n z | n == 0 = z
| mod15 n == 0 = fizzBuzz’ (n – 1) ( z ++ ["FizzBuzz"] )
| mod5 n == 0 = fizzBuzz’ (n – 1) ( z ++ ["Fizz"] )
| mod3 n == 0 = fizzBuzz’ (n – 1) ( z ++ ["Buzz"] )
| otherwise = fizzBuzz’ (n – 1) ( z ++ [show n] )

fizzBuzz :: Integer -> [String]
fizzBuzz n = fizzBuzz’ n []

I have seen more elegant solutions. I am still learning this language. But I am starting to understand the tougher concepts like monads. I program mainly web applications, so I probably will never use it at work. (Mostly I program OO-style instead FP)

But It will teach you all kind of wonderful concepts, like continuations, monads, tail recursion, higher order functions, writing parsers, recursive data structures and much more stuff.

I feel if I mastered it, I never have to fear a job interview.

Edgar Klerks - November 11, 2009

The layout is damaged. This is a very important thing in haskell. To test it, it should be fixed first.

But nevermind, it is more about that learning new things can make you a better programmer. Learning makes you think.

If you can’t solve something like FizzBuzz, you have yet to learn to think. Programming is 90 % thinking and 10 % typing. Of course most programmers can do this in parallel.

495. PlasticineGuy - December 16, 2009

Disappointing for not being able to do such a simple program.
For heaven’s sake, I’m 12 and I managed it.

496. AndrewE - December 16, 2009

i’m new to programming :-)
in python:

for i in range(1, 101):
if i in range(3, 101, 3):#multiples of 3
print(‘fizz’)
if i in range(5, 101, 5):#multiples of 5
print(‘buzz’)
if i in range(15, 101, 15):#multiples of 3 and 5 (or multiples of 15)
print(‘fizzbuzz’)
else:
print(i)

497. AndrewE - December 16, 2009

oops!
# ‘….’ = indents/spaces
for i in range(1, 101):
….if i in range(3, 101, 3):#multiples of 3
……..print(‘fizz’)
……..if i in range(5, 101, 5):#multiples of 5
…………print(‘buzz’)
…………if i in range(15, 101, 15):#multiples of 3 and 5 (or multiples of 15)
…………….print(‘fizzbuzz’)
….else:
print(i)

498. PlasticineGuy - December 17, 2009

Nope, sorry. That will print fizzbuzzfizzbuzz for multiples of 15. Check for 15 first.

499. AndrewE - December 17, 2009

sorry, my bad! u were right PlasticineGuy…thanx! :-)

#’….’ = indents/spaces

for i in range(1, 101):
……..if i in range(15, 101, 15):#multiples of 15
…………….print(‘fizzbuzz’)
……..elif i in range(5, 101, 5):#multiples of 5
print(‘buzz’)
……..elif i in range(3, 101, 3):#multiples of 3
…………….print(‘fizz’)
……..else:
print(i)

Ted K. - April 23, 2011

The three inside ranges should be stored in lists. There’s a good chance that you are repeatedly creating those ranges 271 times too many (I broke up your ‘elif’s and inserted a counter). That can add up to a lot of wasted cycles.

Range_Max = 101
Range_3 = range(3, Range_Max, 3)
Range_5 = range(5, Range_Max, 5)
Range_15 = range(15, Range_Max, 15)

for i in range(1, Range_Max) :

____if i in Range_15 : # Multiples of 15

____elif i in Range_5 : # Multiples of 5

____elif i in Range_3 : # Multiples of 3

L. - January 11, 2012

I would consider anyone checking a second time out of the race tbh .

IMHO such a major lack of logic can lead to overly complex solutions to simple problems — here you’re only adding one check per loop (some made it double .. they beat you at it :p ) but in another case you will be designing an Mloc solution that runs like a tortoise where a Kloc solution running ok was possible.

The ability of a dev to synthesize and simplify is extremely important for extensibility and maintenance – and very often efficiency.

500. PlasticineGuy - December 17, 2009

I was wondering, is there something wrong with this approach to the problem (using continue instead of else-if):
#include
#include

int main(void)
{
….int i;
….for(i = 0; i < 100; i++) {
……..if(i % 15 == 0) {
…………printf("FizzBuzz\n");
…………continue;
……..}
……..if(i % 3 == 0) {
…………printf("Fizz\n");
…………continue;
……..}
……..if(i % 5 == 0) {
…………printf("Buzz\n");
…………continue;
……..}
……..printf("%d\n", i);
….}
….system("PAUSE");
….return 0;
}

501. Peter B - December 25, 2009

DECLARE @num int

SET @num = 1
WHILE @num <= 1000
BEGIN
IF(@num%3) = 0 AND (@num%5) = 0 PRINT 'FIZZBUZZ'ELSE
IF (@num%3) = 0 PRINT 'FIZZ' ELSE
IF(@num%5) = 0 PRINT 'BUZZ'ELSE

PRINT @num

SET @num = @num + 1
END

502. Jakub Nietrzeba - January 7, 2010

Nice and small FizzBuzz in Swi-Prolog:

forall(between(1, 100, X),(
(0 is X mod 15) -> writeln(‘FizzBuzz’);
(0 is X mod 3) -> writeln(‘Fizz’);
(0 is X mod 5) -> writeln(‘Buzz’);
writeln(X))).

503. Dolomedes - January 8, 2010

program Fizz;

{$APPTYPE CONSOLE}

uses
SysUtils;

var
bot:integer;
throw:string;

begin
for bot:=0 to 100 do
begin
if bot mod 3 = 0 then
begin
if bot mod 5 = 0 then
begin
throw:=’FizzBuzz’end
else
throw:=’Fizz’
end
else if bot mod 5 = 0 then
begin
throw:=’Buzz’
end
else
begin
throw:=inttostr(bot);
end;
Writeln(throw);

end;

end.

504. Become a better programmer by taking a shower - January 10, 2010

[...] Start small, especially if you’re a junior programmer, and work your way up. Start with Fizzbuzz, and work your way up to understanding recursion a lot better (I know I still don’t), or [...]

505. Radzikovsky - January 11, 2010

int main()
{
int i;
for (i=1;i<=100;i++)
{
if (i%3==0 && i%5==0)
cout<<"FizzBuzz"<<"\n";
else
if (i%3==0)
cout<<"Fizz"<<"\n";
else
if (i%5==0)
cout<<"Buzz"<<"\n";
else
cout<<i<<"\n";
}
getch();
return 0;
}

i wish i had such an interview

506. PlasticineGuy - January 25, 2010

I don’t like empty function arguments. I like to stick a void in there.

507. Locoluis - January 25, 2010

[[fizz]Plc1+sc]sf[[buzz]Plc1+sc]sb[n]sq[dddd0sc3%0=f5%0=blc0=q[
]P1+d101>a]sa1lax

GNU dc. The newline between [ and ] is required.

508. hugeoid - January 26, 2010

Again, the point of the blog was not to identify the C/VB/Snobol virtuosos but to weed out a large number of candidates who can’t do the basic thinking to understand and solve the problem. Programming will always be about identifying an effective and optionally efficient human-language procedure, and then translating it into the syntax of some computer language or other. The syntax skills can generally be learned and improved, but the thinking skills generally can’t, so you don’t want to waste your time on those who don’t have them.
Say I asked you to solve the problem of swapping a red cup and a green cup on my desk. All the above 1000’s of lines of code are irrelevant. I want you to identify the need to move cup A out of the way, move cup B to A’s place, and then A to B’s place. Without that you’ll never be much of a programmer in my books. Beyond that you may then seek to impress by explaining the options for and benefits of using platform/language-specific improvements and tricks. But don’t let them overtake the first step (I have the constant joy of maintaining code written by a (thankfully-now-)former colleague who always wrote code in such a way as to use his latest flavour-of-the-month technique, without ever thinking to look at what shape the peg was before bashing it into a klein-bottle-shaped hole.)
The other thing is all swinging-dick stuff about how compact your code is. The first language I learnt was APL, and those who know it will know an entire program to read 2 variables, swap them and print them out, can be done in a half-dozen symbols from go to whoa. It is an incredibly compact language – you could probably program the LHC in 20 lines. But compact APL code is also difficult to read, difficult to understand, to verify, debug, fix, test and maintain. It is best written in expanded and structured form as if it were BASIC. In my experience, highly compact *source* code is rarely more efficient, correct, reliable, or maintainable than expanded code that reflects the human-language procedure. So that’s the way you should code, the exception being when heavily-used code needs to be optimised (at the *object* level) for *processing* efficiency, in which case it is documented in comments.
Here then is my code segment for fizzbuzz, which in my view corrects the glaring flaw in ALL the above examples:

# Loop to process integers in sequence.
# Each value is tested to see whether it is a multiple
# of 3, 5 or both. Since multiples of 3 occur most frequently,
# this test is applied first.

A(b).ra->ca=d{a,b}[R]

509. malleswarareddy - February 6, 2010

using SQLserver this is my code to print as you like

Declare @number int;
declare @num int;
set @num=1;
set @number=100;
while(@num<@number)
begin
if((@num%3)=0 and (@num%5)=0)
print 'pizzbuzz';
else if((@num%3)=0)
print 'pizz'
else if((@num%5)=0)
print 'buzz'
else
print @num
set @num=@num+1;
end

510. Michael Hamilton - February 8, 2010

Up much higher in the page people were talking about swapping two variables.

Assuming C++ I would probably do this in real code:
std::swap(a, b);

If, however, someone asked me to implement that function then yes we’d start with a variable:

template
void swap(swapType &left, swapType &right){
const swapType temporary = left;
left = right;
right = temporary;
}

511. PlasticineGuy - February 11, 2010

Using a temporary variable is pretty much the only way to ensure compatability with all types.

512. Hello world or maybe FizzBuzz! « PL/SQL Energy - February 14, 2010

[...] I will try to make it more complex. We will use some “standard”  programming question:http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ [...]

513. Gaby Abed - February 22, 2010

I’m not surprised that some candidates, even qualified ones, get caught up on “simple” questions. It’s like chefs who interview for certain positions, being asked by the owner or head chef to boil an egg or make a salad. Sometimes the elegance in a simple solution can say a lot about a candidate more than any clever explanation to something more complex ever could.

514. Good Technical Interviews Require Good Technical Interview Questions | c o d i n g f r o g s - February 23, 2010

[...] great thing is, apparently even simple problems can be good enough to find out if someone knows how to code.  I wouldn't recommend you rely solely on the simplest, [...]

515. Nick Antonaccio - February 23, 2010

REBOL one-liner in 94 characters:

repeat i 100[j:””if 0 = mod i 3[j:"fizz"]if 0 = mod i 5[j: join j"buzz"]if j =””[j: i]print j]

516. rajeesh - February 24, 2010

why use mod 5 && mod 3, when you can use mod 15

517. jAST - February 24, 2010

for (var i = 1; i <= 100; i++) Console.WriteLine((i % 3 == 0 && i % 5 == 0) ? "FizzBuzz" : ((i % 3 == 0) ? "Fizz" : i.ToString()));

518. jAST - February 24, 2010

@516: The assignment says, “.. that are multiples of both 3 and 5″. It’s obvious why people go for the mod 3 mod 5 solution over mod 15. To me, either solution is fine.

519. Mike - February 24, 2010

Chuck Norris would simply would ask you if the variables really NEEDED swapping and then stare at you until you broke down in tears and admitted that they didn’t. :)

520. bpm - March 4, 2010

Perl example using a table (just to be different)

@t = (‘FizzBuzz’, 0, 0, ‘Fizz’, 0, ‘Buzz’, ‘Fizz’, 0, 0, ‘Fizz’,
‘Buzz’, 0, ‘Fizz’, 0, 0);
print ( ($t[$_ % 15] || $_).”\n”) for 1..100;

521. Russ - March 4, 2010

FizzBuzz reminds me of something like “Only the cool kids smoke”. So many people lining up to show that they too fit in.

522. ptm - March 9, 2010

function fizzBuzz() {
for($i=1;$i<101;++$i){
$fizz = $i % 3;
$buzz = $i % 5;
if($fizz === 0 && $buzz === 0){
echo 'FizzBuzz';
}elseif($fizz === 0){
echo 'Fizz';
}elseif($buzz === 0){
echo 'Buzz';
}else{
echo $i;
}
echo "\n";
}
}

523. PlasticineGuy - March 10, 2010

Every variable in PHP needs the $.

524. Keith - March 11, 2010

“Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.” (Jacob)

A solution that is a bit outside the box:

On the whiteboard, write: A=1 and B=2,
then erase the A&B, write: B=1 and A=2,

ok, when do I start?!

markc86 - March 11, 2010

Thanks for the laugh.

525. FizzBuzz - March 13, 2010

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

526. PlasticineGuy - March 16, 2010

Um… thank you?

527. innovation management - March 17, 2010

innovation management…

[...] Networks and Networking – It begins with a critical review of the literature on knowledge management, arguing that its focus on IT to create a network structure may limit its potential to promote knowledge sharing among social. [...]…

528. Mike - March 19, 2010

This place needs some groovy:

def fizzBuzzData = [fizz:3,buzz:5]
100.times { i ->
println fizzBuzzData.findAll { i % it.value == 0}.keySet().join(“”) ?: i
}

529. Project Euler - Aphoenix.ca - March 23, 2010

[...] I’ve been trying to hone my Python skills, so I Dove Into Python with a vengeance. That didn’t quite sate my desire for crazy coding fun, and my good buddy Sean suggested the Infamous FizzBuzz test. [...]

530. Stringycustard - March 25, 2010

Not sure if this sort of combination solution is done above (noting the number of comments, it’s likely) but an Actionscript solution could be
for(var i:int = 1; i <= 100; i++)
{
var msg:String = "";
if(i % 5 == 0) msg += ("Buzz");
if(i % 3 == 0) msg += ("Fizz");
if(msg.length == 0) trace(i);
else trace(msg);
}

531. John Morrison - March 29, 2010

This is the sort of thing I would like to see. It is clean, simple and
very straightforward.

#include
int main(void)
{
int k;
for(k = 1; k <= 100; k++)
{
if(k % 3 == 0)
printf("fizz");
if(k % 5 == 0)
printf("buzz");
if( (k % 3)*(k % 5) != 0)
printf("%d.", k);
puts("");
}
return 0;
}

532. PlasticineGuy - April 3, 2010

Not really. The logic multiplication is unreliable in practise and is likely to introduce subtle bugs later on.

533. Eddy - April 9, 2010

The shortest I’ve been able to make in C is 81 bytes.

main(){int n=0;while(++n-101)printf(n%5?n%3?”%i”:”Fizz”:”FizzBuzz”+(n%3?4:0),n);}

534. Eddy - April 9, 2010

Actually, I can make it 79 bytes by using the fact that static memory is initialized to zero.

int n;main(){while(++n-101)printf(n%5?n%3?”%i”:”Fizz”:”FizzBuzz”+(n%3?4:0),n);}

Sweet. Under 80 bytes–I guess that’s a one-liner on your typical console.

535. PlasticineGuy - April 10, 2010

You don’t need the int. Variables are int by default if you leave off the type in C (at least, Visual C++’s C compiler).

n;main(){while(++n-101)printf(n%5?n%3?”%i”:”Fizz”:”FizzBuzz”+(n%3?4:0),n);}

536. Prateek - April 29, 2010

Declare @num INT
SET @num = 0

While @num < 100
Begin
SET @num = @num + 1

IF ((Cast(@num/3.00 as VARCHAR) like '%.00%') AND (Cast(@num/5.00 as VARCHAR) like '%.00%'))
BEGIN
PRINT 'FIZZBuzz'
END
ELSE
IF (Cast(@num/3.00 as VARCHAR) like '%.00%')
BEGIN
PRINT 'FIZZ'
END
ELSE
IF (Cast(@num/5.00 as VARCHAR) like '%.00%')
BEGIN
PRINT 'BUZZ'
END
ELSE
PRINT @num
END

537. The Problem with the World Today (and the solution!) · Yerdebugger! - May 8, 2010

[...] will be hired here. If you can’t reverse a string (or, even better yet, write a simple FizzBuzz function or other trivial task) you have no business coding software. I don’t think that you have to [...]

538. Michael D. Hemphill - May 9, 2010

Here it is in Python, just started learning Python. Nice language.

i = 0
while (i < 100):
i = i + 1
if (0 == i%3 and 0 == i%5):
print 'FIZZ BUZZ'
elif 0 == i%5:
print 'BUZZ'
elif 0 == i%3:
print 'FIZZ'
else: print i

I can understand most managers frustration. For something to be so simple, there has been a lot of complex code writing. There was a saying we used in the Army, KISS – Keep It Simple Stupid.

L. - January 11, 2012

Again .. useless checks, failed logic … Why oh why start by checking the least likely case which is in fact dependant on the next two cases etc. etc. etc. you should NOT be coding.

539. Andy Gorman - May 12, 2010

I’d rather see reusable code and good practices than efficiency.

#!/usr/bin/perl
use strict;
use warnings;

my @nums = (1..100);

my @fizzbuzzed = map {fizbuzzify($_)} @nums;

print join(“\n”, @fizzbuzzed);

sub fizbuzzify {
my $num = shift;

my $mod_three = $num % 3;
my $mod_five = $num % 5;

return $num if ($mod_three != 0 and $mod_five != 0);

my $fizz = “Fizz” if ($mod_three == 0);
my $buzz = “Buzz” if ($mod_five == 0);

return sprintf “%s%s”, $fizz, $buzz;
}

540. kaljtgg - May 18, 2010

In c++

#include

using namespace std;
int num=1;
int main()
{
while(num<=100){
if(num % 3==0 && num % 5 == 0)
cout << "Fizzbuzz" << endl;
if(num % 3 == 0 && num % 5 != 0)
cout << "Fizz" << endl;
if(num % 5 == 0 && num % 3 != 0)
cout << "Buzz" << endl;
else{
cout << num << endl;}
num++;
}
}

541. Färdigt programmeringsspråk och den icke programmerande programmeraren « ToggleOn – dit alla noder leder. - May 31, 2010

[...] ett inlägg på Imran On Tech (läs här) observeras att 199 av 200 jobbkandidater inte kan skriva kod alls. After a fair bit of trial and [...]

542. Outsourcing is full of idiots and scam artists « Boffineering - June 9, 2010

[...] Stories abound. [...]

543. Blog aBlog; » Blog Archive » Stranger in a Strange Land - June 18, 2010

[...] Using FizzBuzz to Find Developers who Grok Coding [...]

544. Kevin - June 20, 2010

Perhaps one should start by giving the same question to your existing developers and in so doing gauge the average time and level of skill that exist in your team, then you can either hire somone of similar or more advanced skills depending on the team dynamic.

545. milan - June 30, 2010

lovely discussion

546. muhdazwa - June 30, 2010

Using VB.NET:

For i = 1 To 100
Console.WriteLine( _
IIf(i Mod 3 0 And i Mod 5 0, i, _
IIf(i Mod 3 = 0, “Fizz”, “”) + IIf(i Mod 5 = 0, “Buzz”, “”)))
Next

547. muhdazwa - June 30, 2010

Using VB.NET (negation from above):

For i = 1 To 100
Console.WriteLine( _
IIf(Not (i Mod 3 = 0) And Not (i Mod 5 = 0), i, _
IIf(i Mod 3 = 0, “Fizz”, “”) + IIf(i Mod 5 = 0, “Buzz”, “”)))
Next

548. Tom - July 1, 2010

Is something like this (in C#) too verbose of an answer for this question?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (((i % 3) == 0) || ((i % 5) == 0))
{
if ((i % 3) == 0)
Console.Write("Fizz");
if ((i % 5) == 0)
Console.Write("Buzz");
}
else
Console.Write(i.ToString());

if (i != 100)
Console.Write(",");
}

Console.ReadLine();
}
}
}

549. soni - July 2, 2010

Software testing and test management service = Testign-associates

550. luv2code – For Software Developers Who Luv To Code: Java Architects and Developers – Java EE, J2EE, Blog - July 9, 2010

[...] When you are interviewing job candidates, how do you know if they can really write good code? Do they simply copy/paste previous code from other projects? Or do they lead the development with new and creative code? In an interview, you need to ask only one 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”.  Link to original question [...]

551. Anthony - July 11, 2010

//with additional msg variable
//in actionscript
var msg = ”;
for(var i = 1; i!=101;++i){
if(i%3==0){
msg = ‘Fizz';
}
if(i%5==0){
msg += ‘Buzz';
}
if (msg == ”){
msg = i;
}
trace(msg);
msg=”;
}

//without additional variable
//in actionscript
for(var n = 1; n!=101;++n){
if(n%3 ==0 && n%5 ==0 ){
trace(‘FizzBuzz’);
}else if(n%3==0){
trace(‘Fizz’);
}else if(n%5==0){
trace(‘Buzz’);
}else {
trace(n);
}
//in another language print \n
}

552. Justin LeClair - July 13, 2010

Forgive the PHP; it’s fast:

Also, 1 line!

for($i = 1; $i <= 100; $i++) echo ($i % 3) ? (($i % 5) ? $i." \r\n": "Buzz\r\n"): (($i % 5) ? "Fizz\r\n": "FizzBuzz\r\n");

553. Lymia - July 19, 2010

Solution in Brainfuck:

>++++++++++[<++++++++++>-]< Set p0 to 100
[>+> Start of main loop and sets p1 to 0
  [-] Clears temp tape
  >++++++++++[<++++++++++>-]<+ Set p2 to 101
  <<[->>->+<<<]>>>[-<<<+>>>]< Subtracts p0 from p2
 
  Checks if p2 mod 3 equals 0
  >>+++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[-]]>[-]<<<
  [ If so:
    [-] Cell Clear
    ++++++++++[>++++++++++<-]>++. Print ‘f’
    +++.[-]< Print ‘i’
    [-]+++++++++++[>+++++++++++<-]>+. Print ‘z’
    .[-]<[-] Print ‘z’
    <<[-]>> Clear p1
  ]<
 
  Checks if p2 mod 5 equals 0
  >>+++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[-]]>[-]<<<
  [ If so:
    [-] Cell Clear
    +++++++++[>+++++++++++<-]>-.[-]< Print ‘b’
    [-]+++++++++[>+++++++++++++<-]>. Print ‘u’
    +++++. Print ‘z’
    .[-]< Print ‘z’
    [-] Cell clear
    <<[-]>> Clear p1
  ]<
 
  <[ If none of the previous are true:
    [-] Cell Clear
    >>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<] Seperate digits of number
    >[-]>>[>++++++++[<++++++>-]<.[-]] Print tens digit
    <>++++++++[<++++++>-]<.[-]<<< Print ones digit
  ]>
 
  [-]++++++++++.[-]
<[-]<-] End of main loop and clears p1

And again without comments:

>++++++++++[<++++++++++>-]<[>+>[-]>++++++++++[<++++++++++>-]<+<<[->>->+<<<]>>>[-<<<+>>>]<>>+++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[-]]>[-]<<<[[-]++++++++++[>++++++++++<-]>++.+++.[-]<[-]+++++++++++[>+++++++++++<-]>+..[-]<[-]<<[-]>>]<>>+++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[-]]>[-]<<<[[-]+++++++++[>+++++++++++<-]>-.[-]<[-]+++++++++[>+++++++++++++<-]>.+++++..[-]<[-]<<[-]>>]<<[[-]>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++++[<++++++>-]<.[-]]<>++++++++[<++++++>-]<.[-]<<<]>[-]++++++++++.[-]<[-]<-]

554. Anthony - July 23, 2010

/*I wrote this in in ms paint with my notepad…again took another 1min… If you can’t program this on paper, than you shouldn’t be programing. After I had it written down. I tested it’s speed compared to my other solutions, and this runs faster…774ms to 796ms per 100000ms, while my others solutions, again written on paper, took over 800ms at a minimum*/
var output:String;
for(var n:int=1; n!=101; ++n){
if(n%3==0){
if(n%5==0){
output+=’FizzBuzz\n';
continue;
}
output+=’Fizz\n';
}else if(n%5==0){
output+=’Buzz\n';
}else{
output+=n+’\n';
}
}
trace(output);
//to get rid of the extra line at the end, which I like, instead of tracing output…
//trace(output.substr(0,output.length-1);

Anthony - July 23, 2010

oops meant to say per 100000 steps in the loop.

Anthony - July 23, 2010

wow… shouldn’t type at 4am… try this again…
I was thinking about the fizzbuzz I had written several days ago, so I wrote this in ms paint using my wacom tablet, in order to simulate the feel of writing it on paper. It took another 1 to 2 min, while the other two took about 2.5 min in total each; therefore, about 6 to 7 min total for three versions.

I tested them all to see which was faster, and my latest fizzbuzz loop seems to run the fastest on my machine; however, it uses a variable outside the loop, and only traces everything at the end.

555. Tudo Mol - August 4, 2010

public class FizzBuzz {

public static void main(String[] args) {
String saida = null;
for (int i = 1; i < 101; i++) {
saida = (i%3<1&&i%5<1?"fizzbuzz":i%5<1?"buzz":i%3<1?"fizz":String.valueOf(i));
System.out.println("saida:"+saida);
}

}

}

556. Brothers in Code | Is Your Next Programmer a Moron? - August 11, 2010

[...] After a few candidates we decided it was too data-centric.  My boss forwarded me the fizz-buzz question.  I just couldn't believe what it's author was saying; senior level programmers can't write [...]

557. Buzzing and Fizzing in PHP « Sharon Lee Levy's Blog - August 11, 2010

[...] it can be terribly challenging to find a programmer who can actually code (see http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/. The article cites the following FizzBuzz problem as a way to determine whether a programmer can [...]

558. Jason - August 16, 2010

TSQL the correct way…

WITH
oneto10 (nbr) AS (SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9),
oneto100 (nbr) AS (SELECT u2.nbr * 10 + u1.nbr + 1 FROM oneto10 u1 CROSS JOIN oneto10 u2)
SELECT
CASE
WHEN nbr % 3 = 0 AND nbr % 5 = 0 THEN ‘FIZZBUZZ’
WHEN nbr % 3 = 0 THEN ‘FIZZ’
WHEN nbr % 5 = 0 THEN ‘BUZZ’
ELSE CAST(nbr AS VARCHAR(9)) END
FROM oneto100

559. linq - August 16, 2010

string b = Enumerable.Range(1, 100).Select(e =>
{
return (e % 5 == 0) ?
((e % 3 == 0) ? “FizzBuzz” : “Buzz”) :
(e % 3 == 0) ? “FIzz” : e.ToString();
}
).Aggregate((e, acc) => e + ” ” + acc);
Console.WriteLine(b);

560. Joe Bentley - August 21, 2010

I’m 15, have never made a full program in my life, programmed an example in pseudo-C# code in less than 1 minute 30, how can these people not be able to do this?!? These aren’t programmers, I kinda feel better about myself now because I never thought I was any good at programming at all (because I’ve never even written a full program) but I’m already better than alot of developers out there cuz I can write a simple fizzbang program :P

561. Joe Bentley - August 21, 2010

btw

int main() {
for(int n = 0; i < 101; i++)
{
printf("\n" + n + "\n");
if (n % 3 == 0)
{
printf("Fizz");
}
if (n % 5 == 0)
{
printf("Bang");
}
}
}

Should handle in the case of both being true cuz it has no endline on the Fizz, so if both evaluate true they will literally append to each other, like "FizzBang"

Marcel Kincaid - February 28, 2011

Joe Bentley, you fail.

562. Interview Questions - Push cx - August 23, 2010

[...] Most of the questions are intended to start interesting conversations about the workplace, though a few (“Which source control do you use?”) do have wrong answers (“None.”) that end an interview as quickly as a candidate being unable to solve FizzBuzz. [...]

563. rralf - September 7, 2010

tsql + cte:

with cte as (
select 1 as id
union all
select id+1 from cte where id<100
)
select
case
when (id%15 = 0) then 'FizzBuzz'
when (id%3 = 0) then 'Fizz'
when (id%5 = 0) then 'Buzz'
else STR(id)
end as id
from cte

564. Marc Thibault - September 7, 2010

The better VBA. One pedestrian, the other a little more APLish. Meet the Master.

Public Function fizzbuzz(n As Integer) As String
Select Case 0
Case n Mod 15
fizzbuzz = “FizzBuzz”
Case n Mod 3
fizzbuzz = “Fizz”
Case n Mod 5
fizzbuzz = “Buzz”
Case Else
fizzbuzz = n
End Select
End Function

Public Function fizbuz(n As Integer) As String
a = Array(“”, “Fizz”, “”, “Buzz”, “”)
fizbuz = a(1 + Sgn(n Mod 3)) & a(3 + Sgn(n Mod 5))
fizbuz = IIf(“” = fizbuz, n, fizbuz)
End Function

565. Southern BITS of Technical Goodness » UI / UX – How do you “tech out” a design person? - September 11, 2010

[...] Inheritance – ( i place this last b/c it is the least important (in my mind) as people have shifted towards shallow inheritance hierarchies. The idea being that objects share functionality that would be best nested in super classes.      > What is functional programming and the differences between OOP & functional? This I would characterize in 1 sentence… “Functional programming is largely about treating functions as first class citizens much like OOP treats data (e.g. parameters). This furthered by the idea of using immutable objects so that functions can not alter the parameters passed in but can only result in different outputs. The idea is that functional algorithms should be mathematical (e.g. if A + B goes in, C always comes out). This results in a certain level of certaintly. You can go into code coverage, DDD, BDD, Unit testing, IOC, not to mention technology specific things like LINQ, WCF, EF, MVC, ASP.NET MVC, JQUERY, JavaScript details, yadda yadda yadda. Always, always, always make them write code on a computer like FIZZ FUZZ : http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ [...]

566. reeder - September 20, 2010

If I were looking for a web programmer all you guys who lost everything after < would be shown the door. :)

L. - January 11, 2012

And this is why the webdev industry is full of noobs who know nothing but HTML and PHP . congratulations :)

Who the f* cares if you already know about htmlspecialchars or not – it’s mere details compared to not having logic –

567. reeder - September 21, 2010

Here’s one line of LINQ in C#:

foreach (string s in Enumerable.Range(1, 100).Select(i => i % 15 == 0 ? “FizzBuzz” : i % 3 == 0 ? “Fizz” : i % 5 == 0 ? “Buzz” : i.ToString())) Console.WriteLine(s);

Cheers!

568. Quora - October 2, 2010

What exactly is the FizzBuzz task?…

The inspiration for the interview question is the [group game "Bizz buzz"][1]: > Bizz buzz (also known as fizz buzz, or simply buzz) is a group word game frequently encountered as a drinking game. > Players generally sit in a circle and, starting fro…

569. FizzBuzz test in C# « Jason's Blog - October 13, 2010

[...] that people are using to weed out the less capable developers. In particular the one called FizzBuzz test is quite amazing to me. It isn’t the simplicity of the challenge that gets me it is the fact [...]

570. Are you a good programmer? « wid@world ~$ - October 21, 2010
571. monosky - November 2, 2010

guess the catch was in the fact that the conditional statement for number divisible by 15 should come before the rest..

#include
using namespace std;

int main()
{ int i;
for(i=1; i<101;i++)
if(i%15==0)
cout<<"FizBuzz"<<endl;
else
if(i%5==0)
cout<<"Buzz"<<endl;
else
if((i%3==0))
cout<<"Fiz"<<endl;
else
cout<<i<<endl;
return 0;
}

572. chris - November 3, 2010

I just found a nice solution at stackoverflow:
@echo off
echo 1
echo 2
echo Fizz
echo 4
echo Buzz
echo Fizz
echo 7
echo 8
echo Fizz
echo Buzz
echo 11
echo Fizz
echo 13
echo 14
echo FizzBuzz
.
.
.

and so forth

573. KS Braunsdorf - November 15, 2010

# sed version
n
n
s/.*/Fizz/
n
n
s/.*/Buzz/
n
s/.*/Fizz/
n
n
n
s/.*/Fizz/
n
s/.*/Buzz/
n
n
s/.*/Fizz/
n
n
n
s/.*/FizzBuzz/p
d

Run with sed 100 | sed -f line-above

–ksb

574. KS Braunsdorf - November 15, 2010

Oh, the run is “jot 100 | sed -f lines-above”, I shouldn’t try to type that fast. –ksb

575. chetpot - November 30, 2010

javascript:void(d=”);for(i=1;i<=100;i++){d+=(i%3==0)?((i%5==0)?'FizzBuzz ':'Fizz '):((i%5==0)?'Buzz ':i+' ')};alert(d)

here is a short js url hope it doesn't get butchered during the post

chetpot - November 30, 2010

it did get butchered well only the 2 single quotes in the first void()
here it is without the quotes

javascript:void(d);for(i=1;i<=100;i++){d+=(i%3==0)?((i%5==0)?'FizzBuzz ':'Fizz '):((i%5==0)?'Buzz ':i+' ')};alert(d)

chetpot - November 30, 2010

ok butchered again one more try with double quotes

javascript:void(d=””);for(i=1;i<=100;i++){d+=(i%3==0)?((i%5==0)?'FizzBuzz ':'Fizz '):((i%5==0)?'Buzz ':i+' ')};alert(d)

576. Ryan - December 17, 2010

#include

int main()
{
for (int i = 0; i < 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
printf("FizzBuzz\n");
else
{
if (i % 3 == 0)
printf("Fizz\n");
else if (i % 5 == 0)
printf("Buzz\n");
else
printf("%d\n", i);
}
}
return 0;
}

577. Como contratar malabaristas « La Naturaleza Del Software - December 26, 2010

[...] primero que mido es si el candidato sabe  programar, el filtro FizzBuzz es asombroso, en un post anterior les propuse este test, normalmente esta o una pregunta similar va [...]

578. Fizz-Buzz Code Challenge « CodeFarrell - December 27, 2010

[...] Code Challenge December 26, 2010 // 0 I came across this post outlining a simple coding challenge and thought I’d try to do it in [...]

579. Farrell Kramer - December 27, 2010

I just came across your post and gave it a try. It seemed pretty easy, though I’ve just started learning to code.

Here’s my solution in Python. Hope I got it right. (I printed the ints together with the Fizz/Buzz notations to make the output easier to read.)

i = 0
while i <= 100:
if i != 0 and i % 3 == 0 and i % 5 == 0:
print(i, " Fizz-Buzz")
elif i != 0 and i % 3 == 0:
print(i, " Fizz")
elif i != 0 and i % 5 == 0:
print(i, " Buzz")
else:
print(i)
i = i + 1

L. - January 11, 2012

Again .. useless checks . luckily you admit to being new … but still .. one should realize 15 = 3*5 and checking again and again and again if indeed it is the case looks a bit like fail

580. vinod - December 30, 2010

Wow that is crazy!

I found some good questions to weed out programmers on this site:

http://www.programmerinterview.com

581. Penis Enlargement - Bigger Penis - January 5, 2011

Penis Enlargement is not a Myth, its been done for centuries. Read this very interesting report a see how you can have a Bigger Penis too.

582. Problem 1 | Project Euler: C++ & Python - January 9, 2011

[...] not an exclusive or, that is, multiples of 3 and 5 (i.e. 15) are counted. This is an example of a FizzBuzz [...]

583. Marcao - January 13, 2011

The problem with the idea of the “third variable swap” question, it is not as using two variables is good coding, but if it’s not a stupid way to select candidates. You know only one way, and in your assunption you believe that this is the only way of doing something. That kind of test is only a way of discovering a bad manager, not a bad candidate. sorry.

584. www.christian-rehn.de » SE1: FizzBuzz - January 14, 2011

[...] Der ursprüngliche Post ist der hier. [...]

585. Dinesh - January 19, 2011

Here is the simple code
declare @v1 int;
set @v1=1;
while (@v1<101)
begin
if (@v1%3 =0 and @v1%5 =0)
print 'FizzBuzz'
else
if (@v1%3=0)
print 'Fizz'
else
if(@v1%5 =0)
print 'Buzz'
else

print @v1

set @v1=@v1+1;

end

586. Chris - January 27, 2011

To post 581:

yourPenis ^ biggerPenis ^ yourPenis ^ biggerPenis

done…

587. Eric - February 1, 2011

Python

for x in range(1,101):
print [x,"Fizz","Buzz","Fizz-Buzz"][(x%3==0)+(x%5==0)*2]

588. ari-free - February 7, 2011

I’m not a CS graduate. I just finished chapter 6 in Starting out with C++ by Gaddis:

C++ (indenting may be off but that’s why I don’t use python…)

int main()
{
int num;
const int FIZZ=3, BUZZ=5, FIZZBUZZ=15;
// FIZZBUZZ is a multiple of FIZZ and BUZZ

for (int i=1; i <= 100; i++)
{
num = i;
if (! (i % FIZZBUZZ) )
{
cout << "FizzBuzz" << endl;
} // if (! (i % FIZZBUZZ) )

else if (! (i % FIZZ) )
{
cout << "Fizz" << endl;
} // if (! (i % FIZZ) )

else if (! (i % BUZZ) )
{
cout << "Buzz" << endl;
} // if (! (i % BUZZ) )

else
{
cout << num << endl;
} // else

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

return 0;

} // int main()

ari-free - February 7, 2011

Version 2:
int main()
{
int num;
int fizz = 3, buzz = 5, fizzbuzz;
int endLoop = 100;

fizzbuzz = fizz * buzz; // FIZZBUZZ is a multiple of FIZZ and BUZZ

for (int i=1; i <= endLoop; i++)
{
num = i;
if (! (i % fizzbuzz) )
{
cout << "FizzBuzz" << endl;
} // if (! (i % fizzbuzz) )

else if (! (i % fizz) )
{
cout << "Fizz" << endl;
} // if (! (i % fizz) )

else if (! (i % buzz) )
{
cout << "Buzz" << endl;
} // if (! (i % buzz) )

else
{
cout << num << endl;
} // else

} // for (i = 1; i < endLoop; i++)

return 0;

} // int main()

589. ari-free - February 8, 2011

Nobody even attempted to answer the original question which is why can’t most programmer applicants do this? How were they able to graduate? I can understand if we’re talking about people who majored in the humanities and learned programming on their own with one of the dummies books and a copy/paste point-and-click wizard approach. But something is seriously wrong with the university system if even CS graduates can’t pass this simple test.

590. hotsleeper - February 27, 2011

This comment is for the completely anal rules lawyers out there….

#include
// It’s a string so no replacement is needed.
void main( void )
{
std::cout << "the numbers 1 to 100" << std::endl;
}

591. hotsleeper - February 28, 2011

There should be an “iostream” in angle brackets after the “#include” but it was lost in translation I guess….

592. hotsleeper - February 28, 2011

How strange. I posted 50 seconds apart and got dates on two different days… wonder what will happen if I post again…?

593. Marcel Kincaid - February 28, 2011

“I don’t see the point in avoiding the third variable.”

The point is that someone said that people who don’t start with one should be written off.

As for FizzBuzz, I would hire the person who used this code or equivalent logic:

for( int i = 1; i <= 100; i++ ){
if( (i%3) && (i%5) )
printf("%d", i);
else{
if( !(i%3) ) fputs("Fizz", stdout);
if( !(i%5) ) fputs("Buzz", stdout);
}
putchar('\n');
}

594. Tom Eberhard - March 1, 2011

Uh, unreadable one-liners are cool, but what about maintainability and performance?

// FizzBuzz without costly % operation.
private void FizzBuzzButton_Click(object sender, EventArgs e)
{
int t = 0;
int f = 0;

StringBuilder output = new StringBuilder();

for (int i = 1; i < 101; i++)
{
t++;
f++;
if (t == 3)
{
output.Append("Fizz");
t = 0;
if ( f == 5 )
{
output.Append("Buzz");
f = 0;
}
}
else if (f == 5)
{
output.Append("Buzz");
f = 0;
}
else
{
output.Append(i.ToString());
}
output.AppendLine();
}

textBox1.Text = output.ToString();
}

595. Chris Lyon › FizzBuzz - March 11, 2011

[...] just testing the new blog, so I’ve posted a pointless solution to the FizzBuzz problem: Write a program that prints the numbers from 1 to 100. But for multiples of three print [...]

596. Gristle - March 16, 2011

Typical. Poster makes a good point. Commenters miss the point, use the opportunity to compare their dicks.

Anybody doing any of this “too clever by half” shit in an interview would be right out.

597. Franz-Robert - March 16, 2011

Hi there,

I was wondering if you would mind sharing a couple of other FizzBuzz questions you created over time?

Cheers!
Franz-Robert

598. Visual Studio 2010 and C# at the STI Global City ICT Roadshow 2011 « .NET @ Kape ni LaTtEX - March 19, 2011

[...] presented on Visual Studio 2010 IDE features, along with a "strange" version of FizzBuzz used to demonstrate C# features like generics and lambda [...]

599. Jay Vaughan - March 21, 2011

#include ‹stdio.h>

int main(int argc, char *argv[])
{
int i = 0;
while (++i ‹= 100)
printf(“%s%s%.0d\n”,
((!(i % 3)) ? “fizz” : “”),
(!(i % 5) ? “buzz” : “”),
((i % 3) && (i % 5) ? i : 0));

}

600. Transio - March 21, 2011

Simplest solution possible..

for ($i=1;$i<=100;$i++) echo $i%15?($i%3?($i%5?$i:"Buzz"):"Fizz"):"FizzBuzz";

601. fewf - March 26, 2011

java
public static void main(String[] args) {
// TODO code application logic here
int a = 0;
int b = 0;

for (int i=1; i<=100; i++){
if (i%3==0){
a=1;
}
if (i%5==0){
b=1;
}
if (a==1 && b==1){
System.out.println("FizzBuzz");
}else if (a==1){
System.out.println("Fizz");
}else if (b==1){
System.out.println("Buzz");
}else{
System.out.println(i);
}
a=0;
b=0;
}
}

602. jinzihao - April 3, 2011

Visual Basic:
Private Sub Form_Load()
For i = 1 To 100
If i Mod 3 = 0 Then GoTo 3
If i Mod 5 = 0 Then GoTo 5
GoTo 1
3:
txtMain.Text = txtMain.Text + “Fizz”
GoTo 9
5:
txtMain.Text = txtMain.Text + “Buzz”
GoTo 9
1:
txtMain.Text = txtMain.Text + CStr(i)
GoTo 9
9:
Next i
End Sub

603. Rockstar Developers: With all these groupies around it’s hard to type. « Kav - April 8, 2011

[...] to agree there are a lot of folks out there that can’t code their way out of a paper bag (see FizzBuzz failures), these people aren’t developers. If you want to hire an excellent developer then say that, [...]

604. Guy Zundel - April 13, 2011

I highly recommend this website!

605. Elliot Kave - April 14, 2011

Not sure this posted before but I really like this website

606. A Glance at FizzBuzz » alex lewis - April 20, 2011

[...] FizzBuzz is an extremely simple but widely used programming test.  The gist of it is this: print integers 1 through 100; if the number is divisible by 3, print “Fizz,” and if the number is divisible by 5, print “Buzz.” I put together a quick solution (skip the code if you want to try it yourself) [...]

607. James - April 22, 2011

That’s a fargin’ trick question!

608. Tom M. - April 23, 2011

I’m astounded, this test failed people. Really!?!?. How about I turn the tables around and refuse to work for an employer that doesn’t understand my answer ;-)

;; Racket: fiz-bang… who needs loops?
(((lambda (f)
((lambda (h) (h h))
(lambda (h) (f (lambda args (apply (h h) args))))))
((lambda (max-val)
(lambda (fizzbang)
(lambda (i)
(unless (= max-val i)
(displayln
(cond [(zero? (remainder i 15)) "fizzbang"]
[(zero? (remainder i 3)) "fizz"]
[(zero? (remainder i 5)) "bang"]
[else i]))
(fizzbang (add1 i))))))
100))
1)

609. sigitp - May 5, 2011

interesting, I am a cellular packet core network engineer, but feels challenged to this task.

here is my answer:

http://sigitp.wordpress.com/2011/05/05/using-fizzbuzz-to-find-developers-who-grok-coding/

610. dudeguyman - May 7, 2011

I don’t understand the criticisms for the if/elif/else solution to the fizzbuzz problem. It’s very readable code, compared to writing a convoluted solution in one line. If we’re talking about productivity, readability is essential to accomplish your goal.

611. Quora - May 9, 2011

Which SQL interview questions effectively test depth of experience and knowledge?…

Jeremy: it doesn’t really work that way. If you have a candidate who has somehow stumbled on this list, AND prepared themselves with correct answers, they aren’t necessarily a cheat who knows nothing about SQL :) Compare to the Fizzbuzz test, which i…

612. Haris Buchal - May 13, 2011

It’s funny. This is not just true in development world but also in Systems & Networking as well. I coded for a while myself and almost went to work for M$ after graduating with CS degree. Then decided to switch from programing to better understand the whole cycle and loved networks and systems.

Most of the programmers don’t have a clue what’s going on the infrast. side and vice versa.

Theory is easier than Logic.

That’s why whenever I interview anyone for a job. I ask them logical questions rather than technical questions. I want to see how a person solves a problem.

Here is the code in JAVA.

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

}
}

613. Anon - May 13, 2011

testing
code
tag on this
blog...
coding blog
should have

 tags 

614. The Best Resources on Hiring for Founders - June 1, 2011

[...] A simple technical screening question – by Imran [...]

615. http://www.links.com - June 20, 2011

please see my website

616. Adam Bourg - July 4, 2011

One solution for Fizz buzz in PHP
<?php
for($i=1; $i < 101; $i++)
{
if($i%3==0)
{
if($i%15==0) {
echo "FizzBuzz “;
} else {
echo “Fizz “;
}
} else if($i%5==0)
{
if($i%15==0) {
echo “FizzBuzz “;
} else {
echo “Buzz “;
}
} else
{
echo $i . “”;
}
}
?>

617. Mike Klein - July 19, 2011

Since nobody else
(except for #346.. just read more carefully)
seems to have thrown in the data-driven approach,
I thought I would…
If I were hiring, that would go to the top of the stack.

I’m learning Haskell, so here we go:

module Main where
— for motivation, see http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/
import Data.List (filter, intercalate)
import Data.Maybe (fromJust)

zzDictionary = [(3, "Fizz"), (5, "Buzz")]

n `divides` m = (m `mod` n) == 0 — I suppose it would be nice to use a pipe ‘|’

fizzBuzzFactors n = filter (`divides` n) possibleFizzBuzzFactors
where possibleFizzBuzzFactors = map fst zzDictionary

fizzBuzz n = if null fbFactors
then show n
else concatMap (\factor -> fromJust $ lookup factor zzDictionary) fbFactors
where fbFactors = fizzBuzzFactors n

answer = map fizzBuzz [1..100]
prettyPrint = intercalate “, ”
main = putStrLn $ prettyPrint answer

— Mike Klein (please, no YAGNI comments)

618. Mike Klein - July 19, 2011

For completeness, here’s my first version:

module Main where

main = putStrLn $ prettyPrint answer

isFizz n = (n `rem` 3) == 0
isBuzz n = (n `rem` 5) == 0
fizzBuzz n = case (isFizz n, isBuzz n) of
(True,True) -> “fizzbuzz”
(True,False) -> “fizz”
(False,True) -> “buzz”
(False,False) -> show n

answer = map fizzBuzz [1..100]
prettyPrint = concatMap (++ ” “)

619. Mike Klein - July 20, 2011

AArgh!!! so much for layout languages in blog responses!

620. msangel - July 22, 2011

a=[];for(i=1;i<101;i++){s='';!(i%3)?s+='Fizz':1;if(!(i%5))s+='Buzz';if(s=='')s=i;a[i-1]=s;}console.log(a+'');

— msangel

msangel - July 22, 2011

it is javascript

621. Michael Schmidt (@MichaelRSchmidt) - August 17, 2011

C# – no repeating of strings – come on people, Fizz should appear once and Buzz should appear once. Since it is a console app I can use Console.CursorLeft to see if I have already output… so no temporary variables and no converting to strings.

for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0) Console.Write("Fizz");
if (i % 5 == 0) Console.Write("Buzz");
Console.WriteLine((Console.CursorLeft == 0) ? "{0}" : "", i);
}

622. Uriel’s FizzBuzz - Uriel - August 18, 2011

[...] was referring to post on another blog, imranontech.com, where the author stated that he used the FizzBuzz question to filter out programmers. So, I wanted to try out and see if I could answer the question. Write a [...]

623. Vitalij S. - August 29, 2011

here the simplest solution for me in java pseudocode:
prettyprint was the hardest tough ;-)

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

if(i%3 == 0){
Syso("Fizz")
done = true;
}
if(i%5 == 0) {
Syso("Buzz")
done =true;
}

if ( done == false){
Syso(i);
}
//print linebreak
Syso("\n");
}

624. Vitalij S. - August 29, 2011

Sorry for the double-Guest-post, but just one thing i just remarked:
Why are there so many programmers, which try obfuscate their code, just to fit it in one line ?

On most of the suggestions here i would think: “WTF is he doing here? Ah wait a moment … Fizz .. Buzz, both or the integer … ahh .. what a dick would obfuscated this simple shit like that ?!”

Just remember to code, “like the guy who will maintain it, will be a violent psychopath who knows where you live.”

Dunno from which genius the quote is, but its a good rule to code by ;-)

625. (Code) Golfing at the office - September 7, 2011

[...] Problem 1: implement FizzBuzz: Print the integers 1 to 100, but replace multiples of 3 with “Fizz” and multiples of 5 [...]

626. Quora - September 8, 2011

Which are some good sources for preparing pre-employment tests for hiring fresher programmers for a startup?…

Having some sort of programming test is a great way to filter out weak candidates (although you’ll find others who strongly disagree). I am a fan of a couple of standard exercises that can be completed in just about any programming language and tend w…

627. Franz@Brant.com - September 11, 2011

@Vitali S.:

“Why are there so many programmers, which try obfuscate their code, just to fit it in one line ?”

I guess it is the sort of programmers who think that shortening the source-code will automagically shorten the object code as well =P

628. Vasyl Khrystyuk - September 16, 2011

JavaScript:

_$=[];for($=0;$++<100;){_='';!($%3)?_+='Fizz':1;if(!($%5))_+='Buzz';if(_=='')_=$;_$[$-1]=_;}console.log(_$+'');

629. Gui - September 18, 2011

C#:

static void Main(string[] args)
{
for(int i = 1; i<=100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz" + i.ToString());
}
if (i % 3 == 0)
Console.WriteLine("Fizz");
else if (i % 5 == 0)
Console.WriteLine("Buzz");
}
Console.Read();
}

630. Alex Meiburg - September 28, 2011

Good way to test:
Send them problems from the USACO training set. If they can solve the first few, they’re pretty efficient programmers.
(A bit of help with I/O is always acceptable here – it’s just about algorithmics)

631. Freyaday - September 30, 2011

Axe

.FIZZBUZZ
.this is a comment
For(Q,1,100)
If Q^3
.^ is Axe’s modulo command. A^B is A mod B
Disp “FIZZ”
End
If Q^5
Disp “BUZZ”
End
!If Q^3?Q^5
. A?B is equivalent to C’s A && B
Disp Q
End
Disp i
.Newline
End

Freyaday - September 30, 2011

Whoops, didn’t catch this, but
If Q^3 should be !If Q^3
and
If Q^5 should be !If Q^5
!If is kind of the opposite of If, it executes the code if the condition evaluates to 0 instead of nonzero

632. Hina Naz - December 1, 2011

this is the coolest, thanks! Just what I was looking for. My Favorite Wife SMS
Thank YOu Very Much

633. Jean-Victor Côté - December 19, 2011

Here is an answer in R:
numbers <- 1:100
div3 <- (numbers %% 3 == 0)
div5 <- (numbers %% 5 == 0)
ifelse(div3,ifelse(div5,"Fizz-Buzz","Fizz"),ifelse(div5,"Buzz",numbers))

634. What are some FizzBuzz-type questions for web or SQL developers? | Q&A System - December 21, 2011

[...] I’m reviewing tests for programmers; some of them are a bit out of date. What are some of the FizzBuzz-type questions for web developers and SQL? That is, not too trivial, but still solvable in five to ten minutes [...]

635. Which FizzBuzz solution is the most efficient? | Articulating ideas - January 8, 2012

[...] solution is the most efficient? January 8, 2012 This little “poor-developer filter” was discussed and solved many [...]

636. natural treatment for hemorrhoids at home - February 5, 2012

[...]we came across a cool web site that you simply may delight in. Take a search for those who want[...]

637. milkshake - February 15, 2012

took me about about 3-5 mins to write in php:

$m3=3;
$m5=5;
for($i=1;$i<=100;$i++){
switch($i){

case $m3:
echo "Fizz”;
$m3=($m3+3);
break;
case $m5:
echo “Buzz”;
$m5=($m5+5);
break;
default:
echo “$i”;
}
}

638. clark county auto auction - February 20, 2012

clark county auto auction…

[...]Using FizzBuzz to Find Developers who Grok Coding « Imran On Tech[...]…

639. Certified translator - February 25, 2012

[...]we came across a cool web site which you may get pleasure from. Take a appear for those who want[...]

640. T-SQL FizzBuzz | vincepergolizzi.com - February 28, 2012

[...] thought I would post my T-SQL version of the classic FizzBuzz programmer question, this is the blog post which it originates [...]

641. firehouse subs - March 1, 2012

[...]one of our guests lately suggested the following website[...]

642. Anders - March 7, 2012

took me just below 5 minutes copy pasting each line

Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(“Fizz”);
Console.WriteLine(4);
Console.WriteLine(“Buzz”);
Console.WriteLine(“Fizz”);
Console.WriteLine(7);
Console.WriteLine(8);
Console.WriteLine(“Fizz”);
Console.WriteLine(“Buzz”);
Console.WriteLine(11);
Console.WriteLine(“Fizz”);
Console.WriteLine(13);
Console.WriteLine(14);
Console.WriteLine(“FizzBuzz”);
Console.WriteLine(16);
Console.WriteLine(17);
Console.WriteLine(“Fizz”);
.
,
,
Console.WriteLine(“Buzz”);
:P

643. Raymond Lumsden - March 17, 2012

[...]although websites we backlink to below are considerably not connected to ours, we really feel they are really really worth a go via, so have a look[...]

644. Richard Barnes - March 19, 2012

A multitude of solutions ranging from C to 4th can be found at

http://c2.com/cgi/wiki?FizzBuzzTest

645. http://dream-analysis.org - March 20, 2012

I have to express my thanks to this writer just for bailing me out of this type of condition. As a result of checking throughout the the web and finding views which were not productive, I believed my life was done. Existing minus the answers to the issues you have sorted out by means of this post is a serious case, and the kind that might have in a negative way affected my career if I had not discovered the website. Your actual talents and kindness in taking care of all the things was useful. I don’t know what I would’ve done if I had not come across such a stuff like this. I’m able to now look ahead to my future. Thanks very much for your reliable and results-oriented guide. I won’t hesitate to recommend your web page to anyone who will need guidelines about this problem.

bobs your unlcce - April 20, 2012

I guess that this is your solution to the fizzbuzz problem, but what programming language is it? :-)

646. Wesley - April 3, 2012

import Control.Applicative

check n | n `mod` 15 == 0 = “FizzBuzz”
| n `mod` 5 == 0 = “Buzz”
| n `mod` 3 == 0 = “Fizz”
| otherwise = show n

main = print $ check [1..100]

Wesley - April 3, 2012

The blog removed the call to fmap (in applicative form) that was in between check and [1..100] presumably because it has pointed brackets and thinks I was trying to inject html.

647. Andy - April 9, 2012

Here’s one in R (apologies for lack of line breaks):

fizzbuzz = function(i, multiples = c(3,5), text = c(“Fizz”, “Buzz”)) {
words = text[i %% multiples == 0]
if (length(words) == 0)
as.character(i)
else
paste(words, collapse = “”)
}

sapply(1:100,fizzbuzz)

It’s also more general, e.g., you can call

sapply(1:200,function(x) fizzbuzz(x, c(3,5,7), c(“Fizz”,”Buzz”,”Bang”)))

Also… how about one which generates the naive answer:

unwindfizzbuzz = function(from, to, multiples = c(3,5), text = c(“Fizz”, “Buzz”)) {
res = sapply(from:to,fizzbuzz)
for (r in res) {
cat(“cat(‘”)
cat(r)
cat(“‘,’\\n’)”)
cat(“\n”)
}
}
:-)

> unwindfizzbuzz(1,100)
cat(‘1′,’\n’)
cat(‘2′,’\n’)
cat(‘Fizz’,’\n’)
cat(‘4′,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘7′,’\n’)
cat(‘8′,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’11’,’\n’)
cat(‘Fizz’,’\n’)
cat(’13’,’\n’)
cat(’14’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’16’,’\n’)
cat(’17’,’\n’)
cat(‘Fizz’,’\n’)
cat(’19’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’22’,’\n’)
cat(’23’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’26’,’\n’)
cat(‘Fizz’,’\n’)
cat(’28’,’\n’)
cat(’29’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’31’,’\n’)
cat(’32’,’\n’)
cat(‘Fizz’,’\n’)
cat(’34’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’37’,’\n’)
cat(’38’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’41’,’\n’)
cat(‘Fizz’,’\n’)
cat(’43’,’\n’)
cat(’44’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’46’,’\n’)
cat(’47’,’\n’)
cat(‘Fizz’,’\n’)
cat(’49’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’52’,’\n’)
cat(’53’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’56’,’\n’)
cat(‘Fizz’,’\n’)
cat(’58’,’\n’)
cat(’59’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’61’,’\n’)
cat(’62’,’\n’)
cat(‘Fizz’,’\n’)
cat(’64’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’67’,’\n’)
cat(’68’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’71’,’\n’)
cat(‘Fizz’,’\n’)
cat(’73’,’\n’)
cat(’74’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’76’,’\n’)
cat(’77’,’\n’)
cat(‘Fizz’,’\n’)
cat(’79’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’82’,’\n’)
cat(’83’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)
cat(’86’,’\n’)
cat(‘Fizz’,’\n’)
cat(’88’,’\n’)
cat(’89’,’\n’)
cat(‘FizzBuzz’,’\n’)
cat(’91’,’\n’)
cat(’92’,’\n’)
cat(‘Fizz’,’\n’)
cat(’94’,’\n’)
cat(‘Buzz’,’\n’)
cat(‘Fizz’,’\n’)
cat(’97’,’\n’)
cat(’98’,’\n’)
cat(‘Fizz’,’\n’)
cat(‘Buzz’,’\n’)

648. Pisto - April 11, 2012

What, no Ada?

with Ada.Text_IO;
use Ada.Text_IO;
procedure FizzBuzz is
N : Positive := 100; — Max. count
begin
for i in 1 .. N loop
Put(” “); –nice formatting
if (i mod 15) = 0 then
Put_Line(“Fizz-Buzz”); –newline after every ‘fizzbuzz’
elsif (i mod 3) = 0 then –multiples of 15 can’t fall through
Put(“Fizz”);
elsif (i mod 5) = 0 then
Put(“Buzz”);
else
Put(Integer’Image(i));
end if;
end loop;
end FizzBuzz;

Pisto - April 11, 2012

Ugh, how sloppy of me. For consistency, that should be


else
Put(Positive’Image(i));
end if;

And the comment double dashes rendered into em-dashes…

649. Gui R - April 21, 2012

My implementation in java: http://pastebin.com/XTYeDcNU
I tried to make it as fast/efficient and clean as possible. Suggestion/tips/criticisms welcome.

650. أساحبي - April 22, 2012

While all of you nice people wrote comments, Imran is not having fun on the beach, or dead, i wish him well i don’t know the dude, anyways, what makes a good programmer? MONEY … if you make good money making software you are a good programmer, period.

651. Interviewing Programmers (Or: When FizzBuzz is asking too much) | Brian Williammee - April 22, 2012

[...] entered the software development lexicon in 2007, when Imran Ghory wrote a post about a simple programming problem that can weed out those who just aren’t very good when it [...]

652. MATLAB guy - April 29, 2012

x = 1:100;
out = cellstr( num2str(x(:), ‘%d’) );
out(mod(x,3)==0) = {‘Fizz’};
out(mod(x,5)==0) = {‘Buzz’};
out(mod(x,15)==0) = {‘FizzBuzz’};
disp( strtrim(out) )

653. khaln - May 21, 2012

ksa

654. Luke Peters (@MoonlightLuke) - May 23, 2012

Simple jQuery FizzBuzz script :D Quick and dirty, lol.

http://jsfiddle.net/lukempeters/LEDsG/

655. coder - May 25, 2012
656. Hannes S. - June 15, 2012

Guys, I can’t believe that pure SQL is missing here. ;-)

select
case
when (n % 15) = 0 then ‘FizzBuzz’
when (n % 3) = 0 then ‘Fizz’
when (n % 5) = 0 then ‘Buzz’
else n
end
from (
select (10 * digit2.n) + digit1.n + 1 n
from (
select 0 n union select 1 n union select 2 n union
select 3 n union select 4 n union select 5 n union
select 6 n union select 7 n union select 8 n union
select 9 n
) digit2, (
select 0 n union select 1 n union select 2 n union
select 3 n union select 4 n union select 5 n union
select 6 n union select 7 n union select 8 n union
select 9 n
) digit1
) t;

657. Hannes S. - June 15, 2012

Works at least using SQLite.

Hannes S. - June 15, 2012

Also works in MySQL when adding “order by n” at the end.

658. Matias Persson - June 23, 2012

Lol? This is so stupid. I did this in 2 minutes, and I’m 16 years old.

public class Main {
public static void main(String[] args) {
for(int x = 1; x<=100; x++) {
if(x%3 == 0 && x%5 == 0) {
System.out.println("Fizz-Buzz");
}
else if(x%3 == 0) {
System.out.println("Fizz");
} else if(x%5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(x);
}
}
}
}

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz-Buzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
Fizz-Buzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
Fizz-Buzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
Fizz-Buzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
Fizz-Buzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
Fizz-Buzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

659. juan - June 27, 2012

google: “programming know is number is multiple of 3″ 20 seconds on find the right answer

Gratefuldad0004 - June 27, 2012

How’s this for a 2 minute solution in C?

for( int i = 1 ; i <= 100; i++)
(i%3 && i%5) ? printf("%d\n", i) : printf("%s%s\n", (!(i%3) ? "Fizz" : ""), (!(i%5) ? "Buzz" : ""));

My bit of "wisdom" for the day: if you love coding or developing don't let yourself get sucked into management. It's so much like the Dark Side. :-(

660. ajungren - July 2, 2012

Here’s my (intentionally obfuscated) C version: http://pastebin.com/cFusuLux

You don’t really need the “& 1″ part, but I kept it for consistency. On the plus side, it only does the actual multiple checking once!

661. Bob Fuscated - July 2, 2012

#include
int main(){
int i;
for(i=1; i<=100; i++){
switch((2+i/3-(i+2)/3)*(3+i/5-(i+4)/5)-2){
case 1: printf("Buzz\n"); break;
case 2: printf("Fizz\n"); break;
case 4: printf("FizzBuzz\n"); break;
default: printf("%d\n",i);
}
}

662. Bob Fuscated - July 2, 2012

With escape chars…

#include \
int main(){
int i;
for(i=1; i<=100; i++){
switch((2+i/3-(i+2)/3)*(3+i/5-(i+4)/5)-2){
case 1: printf("Buzz\n"); break;
case 2: printf("Fizz\n"); break;
case 4: printf("FizzBuzz\n"); break;
default: printf("%d\n",i);
}}
return 0;
}

663. Oliver Lassen - July 19, 2012

In Javascript

for(var i = 0; i <= 100; i++){

if (((i % 3) == 0) && ((i % 5) == 0)){
console.log("fizz buzz");
}else if ((i % 5) == 0){
console.log("buzz");
}else if ((i % 3) == 0){
console.log("fizz");
}else{
console.log(i);
}
}

Took me 2 minutes..

664. this blog - August 9, 2012

WOW just what I was searching for. Came here by searching for
3d printers

665. Fizzbuzz and other logic puzzles · Big Ideas by Jezen Thomas - August 23, 2012

[...] first problem is from an article by Imran Ghory. His description of ‘Fizzbuzz’ is as follows. Write a program that prints the numbers [...]

666. nick - August 24, 2012

and in c++ (probably again…im not trawling through all the comments!)

for (int i = 1; i<=100; i++)
{
if ((i%3)==0 && !(i%5) == 0) {
cout << "fizz" << endl;
} else if (!(i%3)==0 && (i%5)==0) {
cout << "buzz" << endl;
} else if ((i%3==0) && (i%5)==0) {
cout << "fizzbuzz" << endl;
} else {
cout << i << endl;
}
}

667. French-Man - August 30, 2012

Pseudo-Code

for i=1 to 100

/*compute the state
n=0
if i modulo 3 == 0 then n = n+2
if i modulo 5 == 0 then n = n+4

/* acting
switch (n)
case 2 : print(“Fizz”) /*(case 010 in binary)
case 4 : print(“Buzz”) /*(case 100 in binary)
case 6 : print(“Fizzz-Buzzz”) /*(case 110 in binary)
default: print(i)

Easier to understand and reading when the states and the actions are separated
Easy to add a condition, like remplacing the multiple 7 by “Big” and 11 by “Bang”
Avoids, prevent the “if / ifelse / else” noodles dish.
Usefull in real life, for example with the options in the sales contract or in a production line.

668. pPromoKristenfzb - September 26, 2012

Hey! nice post you have there. Thank you^^

669. aMailoElrodztdri - September 27, 2012

http://www.elottery888.com There is a vast quantity of facts on the web site you’ve began. Many thanks.

670. pAlingaDogtfg - September 27, 2012

https://twitter.com/#!/CafeNoailles You were given sweet description related to how to update websites

671. jHowNedfkap - September 27, 2012

Love the post! and i love the website, really useful info here

672. wRedBrucevw - September 27, 2012

Really helpful idea for me . br Will you publish some far more ? coz i need to adhere to ur twitter or facebook

673. jAlexJetwe - September 27, 2012

What a super weblog! to very much info and a incredibly short lifestyle hehehehe continue to keep it up, fine function
camper vans hire in Broxburn

674. aWowKierstinduqag - September 28, 2012

http://www.internationaldreams.co.uk/ I believed your article was great and will go to often.

675. aJohnBrucegdqb - September 28, 2012

Excellent post. I was checking continuously this blog and I’m impressed! Very useful information specifically the last part :) I care for such information a lot. I was seeking this certain information for a very long time. Thank you and best of luck.

676. tSueraShanemqmaq - September 28, 2012

http://jointpainpatch.com You’r site is nice and you indeed run your blog for fun.

677. jBoaPromojshw - September 28, 2012

http://www.smithprinting.net/ I have recently discovered your site and enjoy each article. I love your talent.

678. xJohnNasonkehe - September 29, 2012

http://jointpainpatch.com I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this hike.

679. jNazemeShanedxzh - September 30, 2012

http://www.smithprinting.net/ Hmm, there looks to become some difficulties while using initial link, because it returns a 404 error

680. aBlueSierrauqsc - September 30, 2012

Hmm, there looks being some difficulties with the 1st link, because it returns a 404 error

681. oTommyBrucenb - September 30, 2012

http://www.ashevillephotography.co/ I think your comment on the new website ring very true for all. Very well articulated. I see forward to see more here.

682. gNazemeDoleuvfyhx - September 30, 2012

With thanks for this fantastic internet site. I’m trying to go through some more posts but I cant get your web site to display appropriately in my Opera Browser. Many thanks again.

683. bSelsoJordanbqdu - October 1, 2012

http://svideocable.org I need to say that this submit could be the most relevant posting I’ve ever understand and saw. It is a great support to everyone who’s seeking for this info.

684. mBaileysWowajapp - October 1, 2012

http://www.assuryacht.com After examine just a few of the blog posts in your website now, and I really like your method of blogging. I bookmarked it to my bookmark web site record and might be checking again soon. Pls take a look at my site as effectively and let me know what you think.

685. hSeanLegaicx - October 2, 2012

http://gorillastructures.com/BuildYourCarport.html This is definitely wonderful concept dude.iam truly proud of you . Do u have twitter?? i want to stick to you .thx

686. oKaitlinMrxjazf - October 2, 2012

http://www.internationaldreams.co.uk/ FYI, your webpage doesn’t look suitable in Opera.

687. dMaxSolofs - October 3, 2012

http://radionics1.com Be glad of existence mainly because it gives you the chance to love, to function, to play, and to appear up at the stars.

688. bXrShawnug - October 4, 2012

http://spinecentertx.com Oh my goodness! a tremendous article dude. Thanks Nonetheless I’m experiencing challenge with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting an identical rss problem? Anybody who knows kindly respond. Thnkx

689. sJetCodeclek - October 4, 2012

Thanks for taking the time to discuss this, I feel can find any information in article and discus forum
motor homes for hire in Argyll

690. aSelsoRisaentfp - October 4, 2012

http://sanjosebackpainrelief.com Many thanks and Please preserve updating your Webpage. I are going to be stopping by each time you do . br

691. cLegaiMailohbyhg - October 4, 2012

http://alphey.com Youre so cool! I dont suppose Ive learn something like this before. So nice to find anyone with some authentic ideas on this subject. realy thanks for beginning this up. this website is something that is needed on the internet, somebody with a little originality. useful job for bringing something new to the internet!

692. nJasonMrxvhbae - October 4, 2012

http://veneers-cost.com Wow, I have a weblog too but I can’t write at the same time as you do. Very good stuff.

693. hCelsoCodecq - October 5, 2012

http://radionics1.com Like many others, this is my first moment commenting here. I really adore this website and see it pretty often.

694. vKristenLegaifx - October 6, 2012

http://essentialoilsguide.co Hey your site is awesome, I very enjoyed it.

695. lKristenDogyhcckd - October 6, 2012

http://spinecentertx.com Hey your blogs are very nice. It help for my business. Thank you for putting this.

696. yhSoelSeannp - October 8, 2012

I’m from Latvia and I can’t speak english quite well, but this post is really useful.

http://www.google.com

697. aTomAlavjhah - October 8, 2012

http://www.miagenesis.com It’s onerous to search out knowledgeable folks on this subject, but you sound like you already know what you’re talking about! Thanks

698. Harrison Pratt, DO - October 8, 2012

Visual Prolog 5.2 solution for FizzBuzz:
/*
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”.
*/
PREDICATES
fb( integer )
enum_fb( integer, integer )

CLAUSES
fb( I ):-
I mod 3 = 0,
write( “Fizz” ),
I mod 5 0, !.
fb( I ):-
I mod 5 = 0,
write( “Buzz” ), !.
fb( I ):-
write( I ).

enum_fb( N, Last ):- N > Last, !.
enum_fb( N, Last ):-
write( “\n”),
fb( N ),
Next = N + 1,
enum_fb( Next, Last ).

GOAL
enum_fb( 1, 100 ).

699. Rahul - October 13, 2012

#include
#include
using namespace std;

int main()
{
int i;

for(i=1; i<=100; i++)
{
if((i%3)==0)
{
if((i%5)==0)
{
cout<<"FizzBuzz\n";
}

else
{
cout<<"Fizz\n";
}
}

else if((i%5)==0)
{
cout<<"Buzz\n";
}

else
{
cout<<i<<"\n";
}

}

getch();
return 0;
}

700. Zbyszek - October 19, 2012

Unreadable shitty version in JS:

for (var k=2,str=”,A = new Array(‘Fizz’,’Buzz’); k<=((str += (str=='' || str[str.length-1]=='\n' ? k-1 : '')+'\n')?100:0);k++) for (var s in A) if (k%((76-A[s].charCodeAt(0))/2)==0) str += A[s];

window.alert(str);

Every task can be done by many ways. This example is bad in readibility and in performance. Just for fun doing it a bad way. ;)

701. gBaileysChrichtonda - October 19, 2012

https://www.youtube.com/watch?v=kerK5YYKmzQ Wow, I’ve a webpage too but I can’t write as well as you do. Excellent stuff.

702. pTomNeduaejo - October 20, 2012

Hello! useful post you have there. Thank you;)

703. kBoaMaxinejlp - October 21, 2012

Thanks so much for the great advice.

704. tDemodwhololbjom - October 24, 2012

This is really great notion dude.iam genuinely proud of you . br Do u have twitter?? i would like to adhere to you .thx

705. Java Programmer - October 27, 2012

Great questions, this is mostly asked. Thanks

706. yhDoleRoshansgcdo - November 9, 2012

Many thanks for taking the time to discuss this, I feel can discover any info in write-up and discus forum

707. jSelsoCelsoplvyh - November 9, 2012

Hey! I’ve bookmarked your website because you have so cool posts here and I would like to read some more.

708. tKierstinRishanfsa - November 9, 2012

I believed your article was great and will go to typically.

709. dElrodPromodexro - November 10, 2012

This publish was very nicely written, and it also contains a lot of valuable details. I appreciated your professional manner of writing this article. You might have created it simple for me to fully grasp.

710. pShaceSelsoxou - November 10, 2012

I’m not sure where you are getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for fantastic information I was looking for this information for my mission.

711. aRoleDelingaxola - November 10, 2012

Aw, this was a really nice post. In concept I wish to put in writing like this additionally – taking time and actual effort to make a very good article… however what can I say… I procrastinate alot and on no account seem to get something done.

712. jDelingaBjoexfi - November 10, 2012

Cheers and Please maintain updating your Blog. I will be stopping by every single time you do . br

713. FizzBuzz in Erlang | Surviving by Coding - November 10, 2012

[...] I was reading some Erlang, I stumbled upon the term FizzBuzz and how it is used to test programmers (and I just realized that my former employer used this to test me…). I found this Erlang [...]

714. lKierstinAlatn - November 11, 2012

I incredibly a great deal appreciate your website below, thank you so a lot you have helped me out greatly Smile spread the adore.

715. 天空の城のFizz-Buzz | 機上の極論 - November 12, 2012

[...] Using FizzBuzz to Find Developers who Grok Coding – Imran On Tech (2007.1.24) [...]

716. jNasonSierraajei - November 13, 2012

FYI, your blog doesn’t seem suitable in Opera.

717. FizzBuzz Still Works — Global Nerdy - November 15, 2012

[...] I was surprised to find that only one of the candidates had heard of FizzBuzz. I was under the impression that that it had worked its way into the developer world’s collective consciousness since Imran Ghory wrote about the test back in January 2007: [...]

718. Thoughts on IKM Assessment « erlang:get_cookie(). - December 21, 2012

[...] (Ref.: CodingHorror and Imran on Tech) [...]

719. Ali - January 10, 2013

It’s simple:
(In Python)
Ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}
count = 1
while count <= 100:
if count:3 in Ints:
print "Fizz"
elif count:5 in Ints:
print "Buzz"
elif count:15 in Ints:
print "Fizz-Buzz"
else:
print count
count = count+1

720. Alex G - January 16, 2013

I am a first year CS student. Hear is my Java solution:

for (int i = 1; i <= 100; ++i)
{
boolean modThree = (i%3 == 0);
boolean modFive = (i%5 == 0);

if (!modThree && !modFive)
{
System.out.print(i);
}

else
{
if (modThree)
{
System.out.print("Fizz");
}
if (modFive)
{
System.out.print("Buzz");
}
}
System.out.println();
}

721. Teaching Advanced Software Engineering | Semantic Werks - January 25, 2013

[...] are not able to write code (not good code, or even mediocre code – just not write code! See Fizzbuzz). It is very difficult to (defensibly) identify these people, however. One technique which I should [...]

722. How NOT to do technical recruiting: Sunil Kumar of Panzer Solutions : Dragons in the Algorithm - February 1, 2013

[...] But Mr. Kumar didn’t write me about a position commiserate with my specific skills, he wrote to tell me “We have more than 100 W2 working currently with successful hit.” (That’s not quite English, but it’s fairly close.) There are recruiters who work hard to match up a particular applicant with a position where their skills and their career/environment preferences are a good fit. When I am doing the hiring (and just to note, Capital One is hiring right now in the Wilmington area), I love working with these recruiters: they bring me just 3 resumes and I end up wanting to bring in all 3 for further interviews. That’s a much more pleasant experience than digging through a stack of resumes most of whom can’t pass the FizzBuzz test. [...]

723. FizzBuzz…. The sad state of programming talent… | shoelessrob - February 2, 2013

[...] interview programming challenge that is meant to “weed out” people that cannot program ( see http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ for some background). Needless to say I was curious, so I decided to use FizzBuzz in my attempt to [...]

724. Anubhav - February 27, 2013

I like this kind of short exercise in pen and paper, Here another one how to swap two numbers without using temp variable in Java, with couple of more ways

725. Dave - March 6, 2013

I recently started to participate in interviews for new hires as well as co-op students. I prepared some questions for our Java-based web application team. Out of six candidates for full-time positions, all of whom had listed more than 3 years of professional experience in Java on their resume, not a single one was able to answer any of my questions. My manager said I was going too hard on the new hires. I was at a loss.

Example questions I asked (all prefaced with “in the context of Java SE”):

– What is the difference between inheritance and encapsulation?
– What is a difference between a List and a Set?
– What is immutability? Can you give an example?
– Can you explain generics? Are they a compile-time or a run-time construct?

For co-op students, I was unable to find a single student in 3rd or 4th year computer science or engineering that could tell me what the difference between an interface and a class was – one of them was able to after a few minutes of “wait, wait, wait” and flipping through papers.

Am I being unreasonable here? I a