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
Fizzinstead of the number when it is a multiple of3; - print
Buzzinstead when it is a multiple of5; - print
FizzBuzzwhen it is a multiple of both3and5.
Constraints:
- Loop from
1to100included. - 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%3andi%5beforei%15. A number like15then printsFizzand never reaches theFizzBuzzcase. - Forgetting
default, so plain numbers are never printed. - Using
<instead of<=in the loop, which stops at99.
Loops power this whole exercise. Learn them in depth in Loops in Go.