FizzBuzz in Go

Print the numbers 1 to 100, replacing multiples of 3 with Fizz, of 5 with Buzz and of both with FizzBuzz, with a complete tested Go solution.

Level
Easy
Estimated time
15 min
Concepts covered
conditions, boucles

FizzBuzz is the classic interview warm-up: it combines a loop, the modulo operator and a chain of conditions. Getting the order of the checks right is the whole trick.

Statement

Print every number from 1 to 100, one per line, but:

  • print Fizz instead of the number when it is a multiple of 3;
  • print Buzz instead when it is a multiple of 5;
  • print FizzBuzz when it is a multiple of both 3 and 5.

Constraints:

  • Loop from 1 to 100 included.
  • Test the “multiple of both” case first, or handle it explicitly.
  • Print one value per line.

Example

The first fifteen lines of the expected output look like this:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Starter code

package main

import "fmt"

func main() {
	for i := 1; i <= 100; i++ {
		// Print Fizz, Buzz, FizzBuzz or the number.
	}
}

Hints

Hint 1

A number is a multiple of both 3 and 5 exactly when it is a multiple of 15. Check that case before the others.

Hint 2

i%3 == 0 is true for multiples of three, and i%5 == 0 for multiples of five.

Hint 3

A switch with no condition reads cleanly here: put case i%15 == 0 first, then case i%3 == 0, then case i%5 == 0, then a default that prints the number.

Solution

Show the solution
package main

import "fmt"

func main() {
	for i := 1; i <= 100; i++ {
		switch {
		case i%15 == 0:
			fmt.Println("FizzBuzz")
		case i%3 == 0:
			fmt.Println("Fizz")
		case i%5 == 0:
			fmt.Println("Buzz")
		default:
			fmt.Println(i)
		}
	}
}

The for loop walks through every number from 1 to 100. A switch with no expression evaluates each case condition in order and runs the first that is true. Because 15 is the least common multiple of 3 and 5, testing i%15 == 0 first catches the FizzBuzz case before the single-multiple checks can steal it.

Common mistakes:

  • Testing i%3 and i%5 before i%15. A number like 15 then prints Fizz and never reaches the FizzBuzz case.
  • Forgetting default, so plain numbers are never printed.
  • Using < instead of <= in the loop, which stops at 99.

Loops power this whole exercise. Learn them in depth in Loops in Go.

Search

Search runs entirely in your browser.