Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Create a checkerboard pattern with the words "black" and "white"

C++ For Loop: Exercise-66 with Solution

Write code to create a checkerboard pattern with the words "black" and "white".

Pictorial Presentation:

C++ Exercises: Create a checkerboard pattern with the words 'black' and 'white'

Sample Solution:-

C++ Code :

#include <iostream>
using namespace std;

int main()
{
    int i, j, rows;
    string b, w, t;
    b = "black";
    w = "white";
    cout << "\n\n Display checkerboard pattern with the words 'black' and 'white':\n";
    cout << "---------------------------------------------------------------------\n";
    cout << " Input number of rows: ";
    cin >> rows;
    for (i = 1; i <= rows; i++) 
    {
        for (j = 1; j <= rows; j++) 
        {
            if (j % 2 != 0) 
            {
                cout << b;
                if (j < rows) 
                {
                    cout << "-";
                }
            }
            else if (j % 2 == 0) 
            {
                cout << w;
                if (j < rows) 
                {
                    cout << "-";
                }
            }
        }
        t = b;
        b = w;
        w = t;
        cout << endl;
    }
}

Sample Output:

 Display checkerboard pattern with the words 'black' and 'white':      
---------------------------------------------------------------------  
 Input number of rows: 5                                               
black-white-black-white-black                                          
white-black-white-black-white                                          
black-white-black-white-black                                          
white-black-white-black-white                                          
black-white-black-white-black

Flowchart:

Flowchart: Create a checkerboard pattern with the words 'black' and 'white'

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find two's complement of a binary number.
Next: Write a program in C++ to calculate the sum of the series 1·2+2·3+3·4+4.5+5.6+.......

What is the difficulty level of this exercise?