Friday, January 9, 2015

Fizz-Buzz Program in Golang

Like the highly popular Hello World code that we use to learn as our first program in any programming language; Fizz-Buzz is one step ahead which helps us to understand the basic nitty-gritty of a language. Also, it's a popular interview question that can be asked even to experienced programmers to check if s/he can actually write code! 


And you know what, most of them fail to write this even if they are working in the said language for say 4+ years! Has Ctrl+C, Ctrl+V taken a toll on our code writing ability :)

Problem Staement

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “Fizz-Buzz”.

Expected Output Sample [Shown only till 20 and not 100]





FizzBuzz using If / Else
Run this code here at Playground and see the Output.

package main

import "fmt"

func main() {
 for i := 1; i <= 100; i++ {

  if i%15 == 0 {
        fmt.Println("Fizz-Buzz", i)
  } else if i%5 == 0 {
        fmt.Println("Buzz", i)
  } else if i%3 == 0 {
        fmt.Println("fizz", i)
  } else {
        fmt.Println(i)
  }
 }
}


FizzBuzz using Switch

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)
        }
    }
}


Run this code at Playground and see the Output.

Hope this helps you to get started with the basic control flow of Google Go language. Please share your views.
  

3 comments:

  1. Cant seem to get the markdown to play well but here is another example of the first way I did it. Just a different iteration of the 1st answer above.
    https://play.golang.org/p/NBoZj4qKAv


    package main

    import "fmt"

    func main() {

    for i := 1; i <= 100; i++ {
    if i%5 == 0 {
    if i%3 == 0 {
    fmt.Println("fizzbuzz")
    } else {
    fmt.Println("buzz")
    }
    } else if i%3 == 0 {
    fmt.Println("fizz")
    } else {
    fmt.Println(i)
    }
    }
    }

    ReplyDelete
  2. https://play.golang.org/p/FYP1j8rKYW

    ReplyDelete