In: Computer Science
Please, write code in c++. Using iostream library
A chessboard pattern is a pattern that satisfies the
following conditions:
• The pattern has a rectangular shape.
• The pattern contains only the characters '.' (a dot) and 'X' (an
uppercase letter X).
• No two symbols that are horizontally or vertically adjacent are
the same.
• The symbol in the lower left corner of the pattern is '.' (a
dot).
You are given two numbers. N is a number of rows and
M is a number of columns. Write a program that generates
the chessboard pattern with these dimensions, and outputs
it.
Input
The first line contains two numbers N and M (1 ≤
N ≤ 50, 1 ≤ M ≤ 50) separated by a
whitespace.
Output
Output should contain N lines each containing M
symbols that correspond to the generated pattern. Specifically, the
first character of the last row of the output represents the lower
left corner (see example 1).
example:
input:
8 8
output:
X.X.X.X.
.X.X.X.X
X.X.X.X.
.X.X.X.X
X.X.X.X.
.X.X.X.X
X.X.X.X.
.X.X.X.X
// C++ program to generate chessboard pattern
#include <iostream>
using namespace std;
int main()
{
int N, M;
// read the number of rows and columns
cin>>N>>M;
// validate number of rows and columns > 0
if(N > 0 && M > 0)
{
// create an array of N rows and M columns
char chessboard[N][M];
char curr_char; // variable to store the current character
// loop over the number of rows starting from last row to first
row
for(int i=N-1;i>=0;i--)
{
if(i == N-1) // last row, start character will be '.'
curr_char = '.';
else // start character will be opposite of the character from i+1
start row character
{
if(chessboard[i+1][0] == '.')
curr_char = 'X';
else
curr_char = '.';
}
// loop over the columns from start column to end column
for(int j=0;j<M;j++)
{
chessboard[i][j] = curr_char; // set (i,j) to curr_char
// alternate the character
if(curr_char == '.')
curr_char = 'X';
else
curr_char = '.';
}
}
// display the generated chessboard
for(int i=0;i<N;i++){
for(int j=0;j<M;j++)
cout<<chessboard[i][j];
cout<<endl;
}
}
return 0;
}
//end of program
Output: