C++ Arrays

Why we need them:

Arrays are used to manipulate blocks of data in an organized fashion. They allow "matrix" style addressing of data, using the {rows, columns} format. (note that arrays are actually addressed using square brackets.) For instance, you might have anArray[3] [4] = 10.0, which would put a 10.0 into the 4th row (remember off by one!) and fifth column.

To declare an array:

Arrays are very simply declared by FIRST declaring the rows and columns in this format:

const int theRows = 10; // note that the size must be an int, the name is arbitrary, and so is the actual size
const int theColumns = 12;
int ArrayName[theRows] [theColumns];
// note that int is arbitrary, could be any type

Arrays are then addressed by using the following notation:

ArrayName[i] [j] = 3; // where the type of variable (i.e. 3) must match the array type

A sample program:

// example program using functions and arrays
// this program finds the location of randomly placed ones

#include <iostream>
#include <vector>

using namespace std;

const int boardsize = 5;
void addOnes(int tempboard [] [boardsize]);

int main ()
{

srand(time(0));

int board[boardsize] [boardsize] = {0};
// alternatively, you could have done just: int board[boardsize] [boardsize];

// insert 5 random ones
for (int i = 1; i < 6; i=i+1)
    {
    board[rand()%boardsize] [rand()%boardsize] = 1;
    }

// identify the position of the ones
for (int i = 0; i < boardsize; i=i+1)
    {
    for (int j=0; j < boardsize; j=j+1)
        {
        if (board[i] [j] == 1)
            {
            cout<< "A '1' is located at " << i << ", " << j << endl;
            }
        }
    }
cout << endl;

// add three more one's by using a function

addOnes(board);

// check the new position of the ones
for (int i = 0; i < boardsize; i=i+1)
    {
    for (int j=0; j < boardsize; j=j+1)
        {
        if (board[i] [j] == 1)
            {
            cout<< "A '1' is located at " << i << ", " << j << endl;
            }
        }
    }

cout << endl; // add one more carriage return to make the screen look pretty
return 0;
}

/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// add ones function
void addOnes(int tempboard [] [boardsize])
{
for (int i = 1; i < 4; i=i+1)
    {
    tempboard[rand()%boardsize] [rand()%boardsize] = 1;
    }
return;
}

/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////