Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD

 

Multi-Dimensional Arrays (Matrices)

Up until now, all of our arrays have been one-dimensional arrays.  These arrays have had "length", but the "width" (or height) remained as only one cell. 

We are now ready to discuss two-dimensional arrays, called matrices (singular:  matrix).  A matrix resembles a table with rows and columns.

It is possible for arrays to have multiple dimension.  A three dimensional array, for example, has 3 subscripts, where each dimension is represented as a subscript in the array.  While it is possible for arrays to have any number of dimensions, most arrays are of one or two dimensions. 

The elements of a matrix must be of the same data type.


Example:  The Computer Club is participating in a series of Programming Meets.  The table below shows the Club's results, where the maximum score for each contestant in a meet is 25.

Name      Meet  #1 Meet  #2   Meet #3  Meet #4  Meet #5 
Robbins        20 18 22 20 16
Montgomery      18 20 18 21 20
Stevenson        16 18 16 20 24
Norton      25 24 22 24 25

Note:  Although the students' names and the meet numbers are shown, they are not part of the actual data and  are not part of the matrix.  Remember, the data in a two-dimensional array is always of the same data type.

The data displayed in this table consists of 20 values -- four rows by five columns.  This matrix will have 20 cells, or elements.

apmatrix Class:

Just as we used a special header file for arrays, we will also be using a special header file for matrices.  The apmatrix class, implements matrices with "safe" subscripts, similar to what we enjoyed in the apvector class.  If a program attempts to use an out-of-bounds subscript value when working with a matrix, the program will be aborted and an error message will appear. 

When you define storage for a matrix (a multi-dimensional array), you must inform C++ that the array has more than one dimension by putting more than one subscript in parentheses after the array name.  The following declaration would be used to store the data shown in the table above:

apmatrix <int> ClubScores(4 , 5);     // Declares a 2-D array

This declaration creates a matrix with the following subscripted elements:

 

columns

rows

[0][0]  [0][1]  [0][2]  [0][3] [0][4]
[1][0] [1][1] [1][2]  [1][3] [1][4]
[2][0] [2][1] [2][2] [2][3] [2][4]
[3][0] [3][1] [3][2]  [3][3] [3][4]