113k views
4 votes
Write a program checkerboard.cpp that asks the user to input width and height and prints a rectangular checkerboard of the requested size using asterisks and spaces (alternating).

User Aviemet
by
5.3k points

1 Answer

3 votes

Answer:

The program named checkerboard.cpp is given below.

#include <iostream>

using namespace std;

int main() {

// variables to hold dimensions

int width;

int height;

// user input taken for width

cout<<"Enter the width of the checkerboard : ";

cin>>width;

// user input taken for length

cout<<"Enter the height of the checkerboard : ";

cin>>height;

cout<< " " <<endl;

cout<< "Rectangular checkerboard of user's choice " <<endl;

cout<< " " <<endl;

// rectangular checkerboard displayed to the console

for(int h=0; h<height; h++)

{

for(int w=0; w<width; w++)

{

cout<< "*" << " ";

}

cout<< " " <<endl;

}

return 0;

}

OUTPUT

Enter the width of the checkerboard: 9

Enter the height of the checkerboard: 5

Rectangular checkerboard of user's choice

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

Step-by-step explanation:

The program is described below.

1. The variables, width and height, are declared to store the respective values.

2. The variables are declared with integer datatype since dimensions cannot be decimals, they need to be whole numbers.

3. User input is taken for the width and height of the rectangular checkerboard to be printed.

4. To print the rectangular checkerboard, two for loops are used.

5. The outer for loop executes upon the integer variable h beginning from 0 till value of height is achieved.

6. The outer for loop executes upon the integer variable w beginning from 0 till value of width is achieved.

7. For the inner loop, both asterisks and spaces

Are printed alternatively.

8. For every value of h, when the inner for loop execution completes, a new line is inserted.

9. The program ends with return statement.

10. As the question mentions nothing about methods or classes, all the code is written inside the main() method and the program is named as checkerboard.cpp.

User Jotamon
by
5.6k points