Introduction
In this tutorial, we’ll create a simple program to generate a chessboard pattern using the Go programming language. The goal is to print an 8×8 grid resembling a chessboard, where alternating cells are marked with ‘X’ and spaces (or ‘O’) to represent the black and white squares.
Objective
The objective is to create a program that displays a chessboard pattern in the terminal. We will use loops to iterate through the rows and columns, alternating between two symbols to create the pattern.
Go Program to Create Chessboard Pattern
package main
import "fmt"
func main() {
// Define the size of the chessboard (8x8)
rows := 8
cols := 8
// Loop through each row
for i := 0; i < rows; i++ {
// Loop through each column
for j := 0; j < cols; j++ {
// Check if the sum of the row and column indices is even or odd
if (i+j)%2 == 0 {
fmt.Print("X") // Print 'X' for black square
} else {
fmt.Print("O") // Print 'O' for white square
}
}
// Move to the next line after each row
fmt.Println()
}
}
Explanation of the Program Structure
Let’s break down the Go program:
- Package main: The main package is used to define the entry point of the program.
- import “fmt”: The fmt package is imported to allow printing output to the console.
- rows := 8, cols := 8: We define the number of rows and columns of the chessboard. Here, it’s set to 8×8, which is a typical chessboard size.
- Nested loops: The outer loop runs through the rows, while the inner loop iterates through the columns. In each iteration, we check whether the sum of the row and column index is even or odd.
- Conditional check: If the sum of row and column indices is even, we print ‘X’. If it’s odd, we print ‘O’. This alternates the colors of the chessboard squares.
- fmt.Print and fmt.Println: fmt.Print is used to print characters on the same line, and fmt.Println is used to move to the next line after printing a row.
How to Run the Program
- Install Go on your system if you haven’t already. You can download it from the official Go website.
- Create a new file with a .go extension, for example,
chessboard.go
. - Copy and paste the Go program into this file.
- Open a terminal/command prompt and navigate to the directory where the file is saved.
- Run the following command to execute the program:
go run chessboard.go
- The chessboard pattern will be displayed in the terminal window.