FizzBuzz Go Program

 

 

FizzBuzz Program in Go

This program prints numbers from 1 to 100, replacing multiples of 3 with “Fizz”, multiples of 5 with “Buzz”, and multiples of both with “FizzBuzz”. Below is the Go code for the program along with detailed explanations and documentation.

Go Code


// Package main provides the entry point for the program.
package main

import (
    "fmt"
)

// main is the entry point for the program.
func main() {
    // Loop from 1 to 100
    for i := 1; i <= 100; i++ {
        // Check if 'i' is a multiple of both 3 and 5
        if i%3 == 0 && i%5 == 0 {
            fmt.Println("FizzBuzz") // Print "FizzBuzz"
        } else if i%3 == 0 {
            // Check if 'i' is a multiple of 3
            fmt.Println("Fizz") // Print "Fizz"
        } else if i%5 == 0 {
            // Check if 'i' is a multiple of 5
            fmt.Println("Buzz") // Print "Buzz"
        } else {
            // If 'i' is not a multiple of 3 or 5, print the number itself
            fmt.Println(i)
        }
    }
}
    

Program Explanation

The program consists of the following parts:

  • Package main: This is the starting point of the Go program. The main package is required to create an executable program.
  • Import fmt: We import the fmt package to use the fmt.Println function for printing output to the console.
  • func main(): This is the main function where the program execution starts.
  • for loop: The loop runs from 1 to 100 using the syntax for i := 1; i <= 100; i++.
  • Conditional Statements:
    • if i%3 == 0 && i%5 == 0: This condition checks if the number is divisible by both 3 and 5. If true, it prints “FizzBuzz”.
    • else if i%3 == 0: This condition checks if the number is divisible by 3. If true, it prints “Fizz”.
    • else if i%5 == 0: This condition checks if the number is divisible by 5. If true, it prints “Buzz”.
    • else: If none of the above conditions are true, it prints the number itself.

 

Leave a Reply

Your email address will not be published. Required fields are marked *