CODEX

Learning Go Lang Days 26 -Writing Fizz Buzz in Go Lang #100daysofcode

Jonathan Fielding
CodeX

--

Photo by Tanya Santos on Unsplash

Having spent time learning about how to build and deploy an application to Kubernetes I thought I would take some time in my next few days of learning to look at some common coding exercises you get in interviews and how we would solve them in Go Lang.

For my first of these coding exercises I thought I would try the famous Fizz Buzz. In Fizz Buzz, the program prints the numbers 1 to 100 except when the number is divisible by 3 or 5. In these circumstances we do the following:

  • If the number is divisible by 3 we print ‘fizz’,
  • If the number is divisible by 5 print ‘buzz’
  • If the number if divisible by both 3 and 5 print ‘fizzbuzz’.

To tackle this problem we need to check if a number if equally divisible by 3 and 5. To do this we use the remainder arithmetic operator % as follows:

if iterator%3 == 0 {
fmt.Printf("fizz")
}

When we use this operator the answer will be equal to 0 if their is no remainder so it is evenly divisible by the number.

To solve the problem we will need to have 3 such if statements, each matching one of the previously mentioned circumstances. The final code looks as follows:

--

--

Jonathan Fielding
CodeX
Writer for

Staff Engineer working for @Spendesk, speaker about web things, writing about tech, contributor to open source. If you like what I write make sure to follow.