Golang FizzBuzz Implementation Program

In this blog post, we're going to tackle one of the most iconic coding challenges that many developers come across when they are learning a new language or attending an interview - the FizzBuzz problem. 

In this post, we will see how this problem can be elegantly solved using Golang. 

Understanding the FizzBuzz Challenge 

The FizzBuzz problem is straightforward. We are tasked with printing numbers from 1 to 100. However, there are a few twists: 
  • If the number is divisible by 3, we should print "Fizz". 
  • If it's divisible by 5, we print "Buzz".
  •  If the number happens to be divisible by both 3 and 5, we print "FizzBuzz". 
For all other numbers, we simply print the number itself. 

Why FizzBuzz? 

FizzBuzz might seem a bit frivolous, but it's a great problem for beginners because it tests your understanding of loops, conditionals, and operators - fundamental programming concepts. Also, it's a great way to familiarize yourself with the syntax and unique features of a new language. 

FizzBuzz in Go 

Now let's tackle this problem in Go. Go's simple syntax, combined with its powerful switch statement, makes this problem a breeze to solve. 

Here's our 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)
        }
    }
}

How the Go FizzBuzz solution works 

We first start a loop that iterates from 1 to 100. For each iteration, we use the switch statement to check the following cases: 
  • If the number (i) is divisible by 15 (i.e., both 3 and 5), we print "FizzBuzz". We check for divisibility by using the modulus operator (%), which gives the remainder of the division. If the remainder is 0, it means the number is divisible. 
  • If the number is not divisible by 15, we then check if it is divisible by 3. If it is, we print "Fizz". 
  • If the number is not divisible by 3, we then check if it's divisible by 5. If it is, we print "Buzz". 
  • If the number is neither divisible by 15, 3, nor 5, we default to just printing the number itself. 
And there you have it! A simple, elegant solution to the FizzBuzz problem using Go. Not only does this help solidify fundamental programming concepts, but it also gives you a little more insight into the power and simplicity of Go's syntax.

The output of the above program:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

Comments