1 min read

What is Fizzbuzz?

Fizzbuzz is originally a game played in the UK schools to teach division to kids. The kids go around counting out loud from 1, unless the number is divisible by 3 or 5, when they have to say "Fizz" and "Buzz", respectively, or "FizzBuzz" when the number is divisible by both.

It was first proposed as an interview problem in 2007 and came to proemience when influential some people like Jeff Atwood (one of the creators of Stack Overflow) picked up on the subject. The idea is that people who can't really write code cannot do it not only for complex problems but even for the most simple ones. So by proposing a very simple problem, like printing the result of FizzzBuzz for the first 100 integers should be a good way to weed them out.

Without further ado, let's take a look at our solution:

func FizzBuzz(number int) {
	if number%3 == 0 {
		fmt.Print("Fizz")
	}
	if number%5 == 0 {
		fmt.Print("Buzz")
	}
	if number%3 != 0 && number%5 != 0 {
		fmt.Print(number)
	}
	fmt.Println()
}

The FizzBuzz problem could also be called "Introduction to Conditionals".
Mainly what you're doing here is using three different conditionals:

  • Is the number divisible by 3?
  • Is the number divisible by 5?
  • Is the number divisible by none of the above?

A slightly different approach is to the test ahead if the number is divisible by either 5 or 3:

func FizzBuzz(number int) {
    if number%3 == 0 || number%5 != 0 {
       if number%3 == 0 {
		fmt.Print("Fizz")
        }
        if number%5 == 0 {
            fmt.Print("Buzz")
        }
	} else {
    	fmt.Print(number)
    }
	fmt.Println()
}

In this case, we only try to print "Fizz" or "Buzz" in case we know the number is divisible by either one.

You can find the full solution at our Problems repository.