In: Computer Science
Write a program checkerboard3x3.cpp that asks the user to input width and height and prints a checkerboard of 3-by-3 squares. (It should work even if the input dimensions are not a multiple of three.) . Don't use function.
Example 1:
Input width: 16 Input height: 11 Shape: *** *** *** *** *** *** *** *** *** *** *** * *** *** * *** *** * *** *** *** *** *** *** *** *** *** *** *** * *** *** *
Example 2:
Input width: 27 Input height: 27 Shape: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
C++ Program
#include <iostream>
using namespace std;
int main() {
int width,height; // Declare two integer variables width and
height
// input two integer variables
cout<<"Input width: "; cin>>width;
cout<<"Input height: "; cin>>height;
string board = ""; // declare string obj board initialize
""
cout<<"\n\nShape:"<<endl;
for (int i = 0; i < height; ++i) // create for loop i until
height outer loop
{
for (int j = 0, c = '*'; j < width; ++j, c = '*') // create for
loop j and declare initeger c='*' until width
{
// check
condition with bitwise operator 'and' and 'xor' values if it true
c=' '(space)
// calculate
every 3 rows display gap
if (((j / 3) & 1) ^ ((i / 3) & 1))
c = ' ';
board += (char)c; // else, convert c integer into character and
add character '*' into board object
}
board += '\n'; // the control is passed into new line
}
cout <<board; // print the entire string outside for
loops
return 0;
}
OUTPUT-1
Input width: 16
Input height: 11
Shape:
*** *** ***
*** *** ***
*** *** ***
*** *** *
*** *** *
*** *** *
*** *** ***
*** *** ***
*** *** ***
*** *** *
*** *** *
OUTPUT-2
Input width: 27
Input height: 27
Shape:
*** *** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** ***
*** *** *** *** ***
*** *** *** *** ***
*** *** *** *** ***