Program: 2D array of boolean values - flipping and counting


Compile and run on the Raspberry Pi, Apple Mac or Linux PC using GNU or LLVM C++ compiler.

Use CodeBlocks on a Windows PC, or alternatively paste into repl.it

Code below:

// 2D array of bits - Phil Gardner

#include <iostream>
using namespace std;

const int NUM_ROWS = 4;
const int NUM_COLS = 8;

bool grid[NUM_ROWS][NUM_COLS];

// -- -- -- -- -- -- -- --

void setGridToEmpty()
{
    for ( int row = 0;  row < NUM_ROWS;  row++ )
        for ( int col = 0;  col < NUM_COLS;  col++ )
            grid[row][col] = false;
}

// -- -- -- -- -- -- -- --

int countOnes()
{
    int found = 0;
    for ( int row = 0;  row < NUM_ROWS;  row++ )
        for ( int col = 0;  col < NUM_COLS;  col++ )
            if ( grid[row][col] == true )
                found++;

    return found;
}

// -- -- -- -- -- -- -- --

void displayGrid()
{
    cout << endl;
    for ( int row = 0;  row < NUM_ROWS;  row++ )
    {
        cout << '\t';
        for ( int col = 0;  col < NUM_COLS;  col++ )
            cout << grid[row][col];
        cout << endl;
    } // finished displaying whole row
    cout << endl;
}

// -- -- -- -- -- -- -- --

int main()
{
    setGridToEmpty();

    cout << "Enter a row index then a column index" << endl;
    cout << "to flip each item between 0 and 1" << endl;

    int r, c, howManyOnes, oldValue, newValue;

    // Infinite loop begins here!
    do
    {
        // Show the 0s and 1s that the array contains at the moment
        displayGrid();

        // Count how many 1s are in the array and determine
        // whether it contains only 1s

        howManyOnes = countOnes();
        cout << "\tThe array contains " << howManyOnes << " items set to 1" << endl;

        if ( howManyOnes == NUM_ROWS*NUM_COLS )
            cout << "\tAll items are set to 1 at the moment." << endl;
        else
            if ( howManyOnes == 0 )
                cout << "\tNot any 1s in the array at the moment." << endl;
            else
                cout << "\tA mixture of 1s and 0s in the grid." << endl;

        cout << endl;

        // Allow user to choose a particular digit to flip
        cout << "row? 0-" << NUM_ROWS-1 << ": ";
        cin >> r;
        cout << "col? 0-" << NUM_COLS-1 << ": ";
        cin >> c;

        if ( r >= 0  and  r < NUM_ROWS  and  c >= 0  and c < NUM_COLS )
        {
            // Flip the old digit and store the new value back in the array
            oldValue = grid[r][c];
            newValue = not( oldValue );
            grid[r][c] = newValue;
            cout << "Changed grid[" << r << "][" << c << "] from ";
            cout << oldValue << " to " << newValue << endl;
        }
        else
            cout << "Off the grid! Out of range!" << endl;

    } while ( true );
    // Infinite loop section ends here
}