How To Solve FizzBuzz


FizzBuzz is a simple game, often used in interview questions. The idea is to list a range of numbers, and if the number is divisible by 3 output "Fizz", or if the number is divisible by 5 output "Buzz". Finally if the number is divisible by both 3 and 5, output "FizzBuzz". Besides being important to learn if it ever turns up in an interview, it’s also a really good way to learn some basic programming concepts, such as the all important loop and conditional logic, which are a huge part of programming.

First, we pick a range of numbers to try this with. I decided to write a script that looked at numbers 0 to 100 and apply the rules of the game to that range. Then we have to think about how to actually accomplish this with code. Let’s use pseudocode to map this out.

In order to know if we should write “Fizz” or “Buzz”, we have to go through every number in that range. We can do that using a loop. The loop is a way that we can do something again and again, for a defined number of times or as long as we need to. If we’re driving down a street, a loop construct might be thought of as, while my car has gas, keep driving. Or if we know how long we need to drive for, we could say, keep driving for 10 miles. In this loop, we’ll start the first number, 0, then add 1 to get to the next, like so, all the way until we’ve reached 100:

myNumber = 0
WHILE myNumber is less than or equal to 100
  increase myNumber by 1
ENDWHILE

This will continue counting up until we reach 100.

Now we’re going through each number, but the assignment says we need to actually show each number. That means we need to output each one :

myNumber = 0
WHILE myNumber is less than or equal to 100
  OUTPUT myNumber
  increase myNumber by 1
ENDWHILE

If we run this code as is, on our screen, we’ll get a list of all the numbers from 1 to 100. That’s a good start, but now we need to replace some of those numbers, specifically the ones that are divisible by 3, or 5, or both. The first step in that replacement process is checking each number and seeing if it’s divisible by 3, or 5, or both:

myNumber = 0
WHILE myNumber is less than or equal to 100
  OUTPUT myNumber
  IF myNumber is divisible by 3
  ENDIF

  IF myNumber is divisible by 5
  ENDIF
  increase myNumber by 1
ENDWHILE

This sets up the conditional logic we need for this game: if those conditions are true, we will execute some code written inside the IF statement. Conditional logic is how we decide if we are going to do certains things, or not. Some kind of condition is given, such as “is two greater than one?”, and then if that thing is true, we do something. If it’s not true, we just skip it and move on in our program. It’s a lot like driving down a road. Say we are driving to our friends house who lived on Elms street. The directions are, to 1. drive down Main street 2. and turn left onto Elms street. On the way we might pass many streets, but if those streets are not Elms street, we just keep driving. If the street is Elms Street, we turn left.

In this game, if the conditions of the IF statement are true, we will output the words “Fizz”, “Buzz”, and “FizzBuzz”:

myNumber = 0
WHILE myNumber is less than or equal to 100
  OUTPUT myNumber
  IF myNumber is divisible by 3
    OUTPUT “Fizz”
  ENDIF

  IF myNumber is divisible by 5
    OUTPUT “Buzz”
  ENDIF

  increase myNumber by 1
ENDWHILE

That’s the basic idea! We don’t have to explicitly say “OUTPUT FizzBuzz” because when both of the above conditions are true, they will both run, first putting out “Fizz” and then “Buzz” with no space inbetween, the result being “FizzBuzz”. When we put strings like that together to form one string, we are using concatenation.

Let’s see what this logic looks like in a few different languages The first language I tried this in was C. This really was a lot of fun. I love the old-school feel of C and working with a compiler. If you are unfamiliar with programming in C, try to read the code below and compare it to the pseudo code above. Does it look familiar? Is it easy to see how the pseudo code translates into real code? Do you see any unfamiliar or surprising syntax? .

#include<stdio.h>

int main(){
  int count = 0;
  while(count <= 100){
    printf("%d",count);

    if(count % 3 == 0){
     printf(" fizz");
    }

    if(count % 5 == 0){
      printf(" buzz");
    }

    printf("\n");
    count = count + 1;
  }

  return 0;
}

One thing you may have noticed is the % sign. This is the modulo operator, %, and we need this to make it work. The modulo operator is used to preform modular arithmetic, which basically just means counting in a circle (like a clock which repeats after 12) instead of increasing infinitely, and is often used to determine if a number is odd or even in programming. In this case, it returns the remainder of that number when divided by another number. So when we do (count % 3), we get a return value of the remainder of (count/3). When we do (count % 3 == 0), we are asking, “When we divide ‘count’ by 3, is our remainder value equal to 0?” If the answer is yes, then we know that the ‘count’ is divisible by 3, and we print “fizz”. If there’s any other remaining value, then the answer is no, and so we print the value of the number.

After playing with C, I played the game with Ruby:

(1..100).each do|n|
  fizz = if n % 3 == 0 then 'fizz' end
  buzz = if n % 5 == 0 then 'buzz' end
  puts "#{n} #{fizz}#{buzz}"
end

There are probably more efficient ways to write this in Ruby, but this is how I did it, and it works. It also demonstrates, to me, why I love Ruby. It's so amazingly concise, yet expressive. The code is so much shorter in Ruby because Ruby has a different syntax, and a different focus than C does. Ruby allows a coder to write things a lot like how we would say it naturally, with a lot of the focus being on writing things easily and quickly. Try reading it out loud as is. Does it sound natural to you?

Programmer happiness is key in Ruby. A lot tends to happen in each line in Ruby, some of the action being implied or happening behind the scenes. Whereas with C, most things need to be explicitly explained. The programmer needs to describe exactly what needs to happen. How do you feel about the differences between the C code and the Ruby code? Do you find Ruby’s brevity helpful or more confusing?

After Ruby, I tried this game in Go. This was by far the most challenging, as I am a total Go newbie and some things about the language can be, at least to me, just a little bit different or odd. For instance, there are no ternary operators, which gives the programmer the ability to write an IF statement on one line, like IF this is true DO this ELSE DO this ENDIF (just like in the Ruby code above), and working with strings seems to be a little more difficult that I would expect. In order to concatenate a string, which is when we take smaller strings and put them together, I had to pass all the little strings and pass then into a function. For instance, in Ruby we can just do:

puts "#{n} #{fizz}#{buzz}"

but in Go we need to do:

res := fmt.Sprintf(str, n, fizz, buzz)
fmt.Println(res)

That’s not bad, I just found it surprising. I am sure a Go expert would find a much better way to do this:

//this just tells go that this is the main package
package main

//this just tells go that this is the main package
import"fmt"

//here is our main function
func main() {
  var fizz string
  var buzz string

  for n := 0; n <= 100; n++ {
    str := "%d %s%s"
    if n%3 == 0 {
      fizz = "fizz"
    } else {
      fizz = ""
    }
    if n%5 == 0 {
      buzz = "buzz"
    } else {
      buzz = ""
    }
    res := fmt.Sprintf(str, n, fizz, buzz)
    fmt.Println(res)
  }
}

What stands out to you about this code, compared to how it looks in Ruby and C?

I also played the game in php.

<?php

$count = 0;

while($count <=100){
  $fizz = $count % 3 == 0 ? 'fizz' : null;
  $buzz = $count % 5 == 0 ? 'buzz' : null;
  echo "{$count} {$fizz}{$buzz}\n";
  $count += 1;
}

And finally in Python. Unlike the other languages we have used so far, Python does not use any brackets or words to end an IF statement or a WHILE loop, it just uses spacing, 4 spaces exactly, to determine when blocks of code start and stop. So instead of

IF this is true
  do this
ENDIF

we have:

IF this is true
  do this

and that’s it. It is very clean looking, but in large files it can be hard to determine when something ends, and errors due to spacing issues are common, and can be a nuisance. But for a short script like ours, it looks nice:

#!/usr/bin/python

count = 0
while(count <=100):
  fizz = 'fizz' if count % 3 == 0 else ''
  buzz = 'buzz' if count % 5 == 0 else ''
  print count,' ',fizz,buzz
  count = count + 1

FizzBuzz is a good way to practice the fundamentals. And having experience solving little puzzles like this are great for interviews too. When challenges like this arise in an interview situation, the first step is always to break down the problem into small pieces, like we did at the beginning. You don’t have to solve the whole thing, just that first step. Then move onto the next. And keep going until you’re done. Often what interviewers are looking for is good problem solving techniques and the ability to break things down. The specifics of a certain language are less important. Playing games like FizzBuzz can help increase those skills.

How would you solve FizzBuzz? Add your solutions here.