Implement FizzBuzz for 1..n
Implement fizzBuzz(n) that for each i from 1 to n prints: Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of 15, otherwise the number itself. Requirement: a multiple of 15 must print FizzBuzz (not Fizz or Buzz) — check the combined case before the single ones. O(n) time.
func fizzBuzz(n int) {
// your code here
}
Write the implementation.
Loop i from 1 to n with a tagless switch: check i%15 == 0 → FizzBuzz first, then i%3 == 0 → Fizz, then i%5 == 0 → Buzz, else print i. The %15 case must be first, or i%3 would match multiples of 15 and FizzBuzz never prints. O(n) time.
- ✗Checking
i%3ori%5beforei%15, soFizzBuzznever prints - ✗Assuming Go
switchfalls through to later cases by default - ✗Forgetting that 15 is the LCM that must be tested first
- →Why does Go's
switchstop at the first matching case withoutfallthrough? - →How would you make the divisor/word pairs configurable instead of hard-coded?
Task
For i from 1 to n: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of 15, otherwise the number itself.
func fizzBuzz(n int) {
for i := 1; i <= n; 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)
}
}
}
Why %15 first
A tagless switch in Go evaluates cases top to bottom and runs the first true one, with no fallthrough by default. A multiple of 15 is true for all three conditions, so if you place i%3 or i%5 above i%15, that fires and FizzBuzz never prints.
15 is the least common multiple of 3 and 5, so the most specific case must come first.
⚠️ A warm-up that checks clean control flow and the knowledge that Go's switch does not fall through.