Multidimensional Arrays
Finally we'll take a look at multi-dimensional
arrays. So far we've seen one-dimensional arrays.
int marks[10];
is a one-dimensional array. It is called one
dimensional because it has only one value inside the square brackets. C++ has no limit on the number of dimensions. You
can have 2 or 3 or more dimension arrays. But we shall take a look at two
dimensional arrays since they will be used frequently.
Consider a two dimensional array as a tabular
column with rows and columns.
int marks[3][4];
declares a two dimensional array with 3 rows and
4 columns.
COLUMNS ARE VERTICAL AND ROWS ARE HORIZONTAL.
COLUMNS
|
marks[0][0] |
marks[0][1] |
marks[0][2] |
marks[0][3] |
|
marks[1][0] |
marks[1][1] |
marks[1][2] |
marks[1][3] |
|
marks[2][0] |
marks[2][1] |
marks[2][2] |
marks[2][3] |
As you can see marks[0][0] is the first square. The compiler always starts from zero and not one. Hence there are three rows and four columns in the array marks[3][4] as shown in the table above. There are a total of 12 elements.
How to get values for an array? (Hint for Project 3)
To get the values for an array you have two ways. You have to keep asking the user statement by statement to enter a value. Or you could make use of the for loop. The best way to get the input for arrays is by making use of the for loop.
Consider the following : You want to get the values of elements of a 2 x 2 matrix (I hope you already know about matrices used in maths. If you don't then kindly email me a message : ssbell2000@yahoo.com).
A 2 x 2 matrix has two rows and two columns. The code will be as follows :
int i, j, a[2][2];
for (i = 0 ; i<2 ; i ++)
{
for (j = 0
; j<2 ; j++)
{
cout<< "Enter the "<< i + 1<< " x
"<< j + 1 <<"element of the matrix : ";
cin>> a[ i ][ j ];
}
}
I think the above code is easy to understand. For i = 0, you will have two values of j (0 and 1). Hence with this you can get the values for a[0][0] and a[0][1]. This corresponds to the first row of the matrix. For the second row, the i for loop will execute a second time with a value of 1. Hence you will get values for a[1][0] and a[1][1].
In the cout statement I have mentioned i + 1 and j + 1. This is just for the display. Remember that the compiler will start numbering from zero. The first element for the compiler will be the 0 x 0 element. For the user it is better if you refer to the first element as 1 x 1.
You'll understand the usefulness of two dimensional arrays in the Projects Section 3
or you can go back to Contents
Copyright © 2002 Sethu Subramanian All rights reserved.