Cute FTP Pro

Arrays Continued


The following topics are covered in this section:


Cute FTP Pro
Multidimensional Arrays

So far we've only dealt with 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. Or in other words, this array will have only a single row of elements. C++ has no limit on the number of dimensions. You can have 2 or 3 or more dimension arrays. Multi-dimensional arrays are actually arrays of 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.

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’ as shown in the table above. There are a total of 12 elements.

The element in row 0 and column 0 can be referred to as the ‘0 x 0’ element. The element marks[0][1] will thus be called as ‘0 x 1’ element. Always remember that the row number comes first. This is not a universal method of referring to array elements. It is used here to make it easier to refer to the elements instead of using the element names.

Obtaining inputs for multi-dimensional arrays:

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 take advantage of the ‘for’ loop (or any of the other looping mechanisms). We have already seen this in the sorting example involving a one-dimension array. The method to obtain the values of elements of a 2 x 2 matrix is similar to that for a one-dimensional array:

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 ];
}
}
The outer ‘for’ loop starts with a value of 0.
i = 0

Corresponding to i=0 we will have two values for 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’ loop will execute a second time with a value of 1. Hence you can get the values for a[1][0] and a[1][1].

In the cout statement we have mentioned ‘i + 1’ and ‘j + 1’. This is just for the purpose of 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 rather than referring to it as 0 x 0.

Similarly, two ‘for’ loops can be used to display the values of a two-dimensional array.


Initializing multi-dimensional arrays:

Initializing a 2-D array is similar to that of a 1-D array.

      int marks[2][3]={ 40,50,60,
                                   70,80,90};

The above notation is used for readability. You might as well initialize the array as:

      int marks[2][3]={ 40,50,60, 70,80,90};

Thus if you use the following initialization (hoping that marks[0][2] will be 0):

      int marks[2][3]={ 40,50,
                                   70,80,90};

the compiler will treat it as:

      int marks[2][3]={ 40,50,70,80,90};

and marks[0][2] will be 70 while marks[1][2] will be 0. Only trailing elements will be automatically initialized to 0. There is a better way to initialize multi-dimensional arrays. The following initialization:

      int marks[2][3]={
                                          {40,50},
                                          {70,80,90}
                                  };

actually produces the result we were looking for earlier. Now, marks[0][2] is zero. The additional pair of parentheses makes a big difference. Readability is improved further and now the compiler will set the trailing elements (which haven’t been initialized) in each row to 0. In our case, only the 3rd element of the first row is missing and hence this is initialized to zero. 

You might recollect that in one dimensional arrays we could specify:

            int a[] = {1,2,3};

and the compiler would translate this into:

            int a[3] = {1,2,3};

The question arises as to whether we can extend this to 2-D arrays as well:

int marks[ ][ ]={
                                          {40,50},
                                          {70,80,90}
                                  };

This will give a compile-time error. The compiler wouldn’t know how many columns you want to specify for the array (you’ll understand this concept when we deal with pointers and 2-D arrays in the next chapter). But for the time being remember that you can forget the 1st dimension but shouldn’t leave out the subsequent ones. 

Let’s go one step further. What is a 3-D array?

            int a[5];

            int ab[2][5];

            int abc[3][2][5];

‘ab’ is a 2-D array which consists of 2 one dimensional arrays (each of which can hold 5 elements). ‘abc’ is a 3-D array which consists of 3 two dimensional arrays (each of the 2-D arrays contains a 1-D array which can hold 5 elements). The concept can be extended to higher dimension arrays as well (but generally we wouldn’t use more than 3 dimensions).  

How do we initialize a 3-D array?

      int abc[3][3][2]={
                                                      {
                                                                  {40,50},
                                                                  {10,70},
                                                                  {20,30}
                                                      },

                                                      {
                                                                  {45,55},
                                                                  {15,75},
                                                                  {25,35}
                                                      }
                                          };

The parentheses make the initialization pretty clear. Of course you can remove all the braces but the declaration wouldn’t be easy to understand. Again in the case of a 3-D arrays, you can drop the first dimension but should mention the other 2.

The following declaration is legal:

      int abc[ ][3][2]={
                                                      {
                                                                  {40,50},
                                                                  {10,70},
                                                                  {20,30}
                                                      },
                                                      {
                                                                  {45,55},
                                                                  {15,75},
                                                                  {25,35}
                                                      }
                                          };

You’ll have to take care of the braces. In the above example:

            abc[0][0][0] = 40
            abc[0][0][1] = 50
            abc[0][1][0] = 10
            abc[0][1][1] = 70
            abc[0][2][0] = 20
            abc[0][2][1] = 30        

What happens in the following declaration?

      int abc[ ][3][2]={
                                                                  {40,50},
                                                                  {10,70},
                                                                  {20,30},
                                                                  {45,55},
                                                                  {15,75},
                                                                  {25,35}
                                          };

All that we’ve done is removed the braces which were used to denote that the 1st dimension was 2. But the compiler isn’t smart enough to know what’s on our mind and now it would create the array as: int abc[5][3][2].

            abc[0][0][0] = 40
            abc[0][0][1] = 50
            abc[0][1][0] = 0
            abc[0][1][1] = 0
            abc[0][2][0] = 0
            abc[0][2][1] = 0          
            abc[1][0][0] = 10
            abc[1][0][1] = 70
            abc[1][1][0] = 0
            abc[1][1][1] = 0
            abc[1][2][0] = 0
            abc[1][2][1] = 0

and so on.

Moral of the story is that you should do your best to make things explicit when dealing with computers rather than assume that the computer would think the way you’re thinking.


Passing an Array to a Function

This topic is dealt with in depth when discussing about pointers. A simple method of passing arrays to functions is illustrated below: #include <iostream.h>

void disp(int a[ ] )
{
    for (int i=0;i<3;i++)
    {
    cout<<endl<<a[i];
    }
}
int main( )
{
int marks[3]={60,70,80};
disp(marks);
return 0;
}
The output is: 60 70 80 Instead of: void disp(int a[ ] ) you could also have used: void disp(int a[3] ) This will also work. Even if you type: void disp(int a[5] )

it will still work. We shall see more about arrays in the chapter on pointers (because arrays and pointers are closely related).

Remember: The compiler will not allocate memory or create an array called a[5] when it is present in the function header. This is just to tell the compiler that an array with a maximum of 5 elements will be passed to the function. Of course you could specify it as a[2], because in effect only the address of the array will be passed. More about this in the section on pointers.


Test Yourself on Multi-Dimensional Arrays

It is a very common program in schools and colleges. Most of the students tend to mug up the coding and reproduce it at the time of the examination. Of course most of them succeed in doing so (the brain is the best memory device in the world!) but some tend to forget one line of coding and end up with weird outputs. Never mug up programs. Understand the logic of the program and then try it yourself. After all, if your logic is correct then there is no chance that the computer will produce wrong results (it will be as good as you program it to be). Let’s write a program to add two matrices (matrices are two dimensional arrays used in mathematics). The various steps involved are:

//To obtain two matrices and two find their sum #include<iostream.h>
#include<iomanip.h>            
//needed for using the manipulator setw ( )
int main( )
{
int i , j , r1 , r2 , c1 , c2 , a[20][20] , b[20][20] , c[20][20];
cout<<"Enter the number of rows and columns of first matrix :";
cin>>r1>>c1;
cout<<"Enter the number of rows and columns of second matrix :";
cin>>r2>>c2;

// If the matrix orders are not equal then addition is not possible
if ( (r1! = r2) || (c1!=c2) )
{
            cout<<endl<<"Matrix addition is not possible";
            return 0;
}

// If orders are equal then get input for two matrices ‘a’ and ‘b’
for (i =0; i< r1; i ++)
{
    for (j = 0; j<c1; j ++)
    {
                cout<<"Enter the "<< i <<" x "<< j <<" element of first matrix: ";
                cin>>a[ i ][ j ];
    }
}
for (i = 0; i<r2 ; i ++)
{
        for (j =0; j<c2; j ++)
        {
                cout<<"Enter the "<<i<<"x"<<j<<" element of second matrix: ";
                cin>>b[ i ] [ j ];
        }
 }
cout<<endl;
// Displaying matrix ‘a’
for (i =0; i<r1; i++)
{
    cout<<endl;
    for (j =0; j<c1; j++)
    {
        cout<<setw(9)<<a[ i ][ j ];
    }
}
cout<<"\t"<<"+";
cout<<endl;
// Displaying matrix ‘b’
for (i = 0; i<r1; i ++)
{
    cout<<endl;
    for (j =0; j<c1; j++)
    {
        cout<<setw(9)<<b[ i ] [ j ];
    }
}
cout<<endl;
cout<<"\t \t \t = ";
cout<<endl;                 
   // Calculating and displaying the result which is stored in matrix ‘c’
for (i =0; i<r1; i++)
{
cout<<endl;
    for (j =0; j<c1; j++)
    {
            c[ i ][ j ] = a[ i ][ j ] + b[ i ][ j ];
            cout<<setw(9)<<c[ i ][ j ];
    }
 }
return 0;
}
setw ( ) will be explained later on. It is a manipulator that is used to format the way the output is displayed.

Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.