Introduction
In this guide, you will learn how to generate a chessboard pattern using C++ programming. The chessboard consists of alternating squares of two colors (black and white), similar to what you see in a real chessboard. This program demonstrates how to use loops to control the display of characters in a matrix format.
Objective
The main objective of this program is to create a square matrix that simulates a chessboard pattern. The program will alternate between two characters, representing black and white squares, to create the desired pattern.
Code
#include
using namespace std;
int main() {
int size; // Size of the chessboard
// Ask the user for the size of the chessboard
cout << “Enter the size of the chessboard (e.g., 8 for an 8×8 board): “; cin >> size;
// Generate the chessboard pattern
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// Use a ternary operator to alternate between ‘#’ and ‘ ‘ (space)
if ((i + j) % 2 == 0) {
cout << “# “; // Black square
} else {
cout << ” “; // White square
}
}
cout << endl;
}
return 0;
}
Explanation of the Program
This program prompts the user to enter the size of the chessboard (e.g., 8 for an 8×8 grid). It then uses nested for
loops to iterate through each row and column of the chessboard matrix.
The pattern is created using an if
statement within the inner loop. The expression (i + j) % 2 == 0
checks whether the sum of the current row index i
and column index j
is even or odd. If it is even, a black square (“#”) is printed, and if it is odd, a white square (represented by a space) is printed.
The outer loop controls the rows of the chessboard, while the inner loop handles the columns. After completing one row, the program moves to the next line, forming the alternating pattern of black and white squares.
How to Run the Program
- Open your C++ development environment or a code editor.
- Create a new C++ file (e.g.,
chessboard.cpp
). - Copy the provided code into the new file.
- Compile the code using a C++ compiler.
- Run the executable, and the program will ask you to input the size of the chessboard.
- Enter a number, such as 8, and the chessboard pattern will be displayed in your terminal.