2-Dimensional Arrays

So far, we've been looking at 1-Dimensional (1D) arrays. You can imagine a 1D array as a row of boxes. Now, picture a 2-Dimensional (2D) array a sheet of graph paper - you can store values (integers, floats, doubles, chars, bools) in these rows and columns of boxes.

Let's take a look at a simple example of a 2D array :

// file : 2d.C
// lame program to demonstrate basics of 2D arrays
#include <iostream.h>
const int ROWS=4;
const int COLUMNS=7;
int main()
{
  char array[ROWS][COLUMNS]; // creates the 2D array of characters
  int i;

  // put some junk in the array
  array[0][3]='k';
  array[ROWS-1][COLUMNS-1]='z';
  for (i=0 ; i<ROWS ; i++)
    array[i][i] = 'A' + i;
  for (i=0 ; i<COLUMNS ; i++)
    array[2][i]='X';
  
  // print out some of that junk to confirm that it's there
  cout << array[0][3] << endl;
  cout << array[1][1] << endl;
  cout << array[2][5] << array[2][6] << endl;

  // 2D arrays can be used in comparisons also
  if (array[0][3]=='k')
    cout << "uh huh..." << endl;
  else
    cout << "nope" << endl;

  if (array[1][1]=='B')
    cout << "yup" << endl;
  else
    cout << "not a 'B'" << endl;

  return 0;
}










Now let's do something more useful with arrays. Consider the following :

// file : matrix.C
// this program multiplies two 3x3 matrices together
#include <iostream.h>
const int SIZE=3;
int main()
{
  int A[SIZE][SIZE];  int B[SIZE][SIZE];  int R[SIZE][SIZE];
  int r,c;

  // nested 'for' loops to cycles through the entire array - this
  // is new and is extremely important to understand
  cout << "Enter the values for the first matrix :" << endl;
  for (r=0 ; r<SIZE ; r++)
    for (c=0 ; c<SIZE ; c++)
      cin >> A[r][c];
  cout << "Enter the values for the second matrix :" << endl;
  for (r=0 ; r<SIZE ; r++)
    for (c=0 ; c<SIZE ; c++)
      cin >> B[r][c];

  // now multiply them together
  R[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0];
  R[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1] + A[0][2]*B[2][1];
  R[0][2] = A[0][0]*B[0][2] + A[0][1]*B[1][2] + A[0][2]*B[2][2];
  R[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0] + A[1][2]*B[2][0];
  R[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[1][2]*B[2][1];
  R[1][2] = A[1][0]*B[0][2] + A[1][1]*B[1][2] + A[1][2]*B[2][2];
  R[2][0] = A[2][0]*B[0][0] + A[2][1]*B[1][0] + A[2][2]*B[2][0];
  R[2][1] = A[2][0]*B[0][1] + A[2][1]*B[1][1] + A[2][2]*B[2][1];
  R[2][2] = A[2][0]*B[0][2] + A[2][1]*B[1][2] + A[2][2]*B[2][2];

  // print out the resulting matrix
  cout << "The resultant matrix is" << endl;
  for (r=0 ; r<SIZE ; r++)
    {
      for (c=0 ; c<SIZE ; c++)
        cout << R[r][c] << "\t";
      cout << endl;
    }
   
  return 0;
}