Introduction
In this program, we are going to print numbers from 1 to 100 following some specific rules:
- If the number is divisible by 3, print “Fizz”.
- If the number is divisible by 5, print “Buzz”.
- If the number is divisible by both 3 and 5, print “FizzBuzz”.
- If the number is neither divisible by 3 nor 5, just print the number.
This is a classic problem known as the “FizzBuzz” problem, commonly used in programming interviews.
Objective
The goal of this program is to help you understand how conditional statements and loops work in Go programming. By the end of this exercise, you should be able to create similar programs that involve loops and condition-based outputs.
Go Program Code
package main import "fmt" func main() { // Loop through numbers from 1 to 100 for i := 1; i <= 100; i++ { // Check divisibility by 3 and 5 if i % 3 == 0 && i % 5 == 0 { fmt.Println("FizzBuzz") } else if i % 3 == 0 { fmt.Println("Fizz") } else if i % 5 == 0 { fmt.Println("Buzz") } else { fmt.Println(i) } } }
Explanation of the Program Structure
Let’s break down the structure of the Go program:
- Package Declaration: The program starts with
package main
. This indicates that the program is a standalone application and not part of a library. - Import Statement: The
import "fmt"
statement allows us to use thefmt
package, which is used for formatted I/O operations like printing to the console. - Main Function: The
main()
function is where the program execution starts. - Loop: We use a
for
loop to iterate from 1 to 100. The loop variablei
starts at 1 and increments by 1 until it reaches 100. - Conditionals: Inside the loop, we check:
- If
i
is divisible by both 3 and 5, print “FizzBuzz”. - If only divisible by 3, print “Fizz”.
- If only divisible by 5, print “Buzz”.
- If none of the conditions are met, print the number itself.
- If
How to Run the Program
- Install Go: If you don’t have Go installed, download it from the official website: Go Downloads.
- Create a New File: Create a new file with the extension
.go (e.g.,
fizzbuzz.go
). - Write the Code: Copy and paste the Go code into the file.
- Run the Program: Open a terminal or command prompt and navigate to the directory where the file is saved. Run the program using the following command:
go run fizzbuzz.go
This will print the numbers from 1 to 100 with the appropriate “Fizz”, “Buzz”, or “FizzBuzz” replacements.