Arrays Continued

The following topics are covered in this section:

Multidimensional Arrays

So far we've only dealt with one-dimensional arrays.
int marks;
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;
declares a two dimensional array with 3 rows and 4 columns. Columns are vertical and rows are horizontal.

 marks marks marks marks marks marks marks marks marks marks marks marks

As you can see marks 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 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;
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 and a. 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 and a.

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={ 40,50,60,
70,80,90};

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

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

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

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

the compiler will treat it as:

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

and marks will be 70 while marks 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={
{40,50},
{70,80,90}
};

actually produces the result we were looking for earlier. Now, marks 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 = {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;

int ab;

int abc;

‘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={
{
{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[ ]={
{
{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 = 40
abc = 50
abc = 10
abc = 70
abc = 20
abc = 30

What happens in the following declaration?

int abc[ ]={
{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.

abc = 40
abc = 50
abc = 0
abc = 0
abc = 0
abc = 0
abc = 10
abc = 70
abc = 0
abc = 0
abc = 0
abc = 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={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 ) This will also work. Even if you type: void disp(int a )

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 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, 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:

Ask the user for the order of the matrix (i.e. the number of rows and columns) To add 2 matrices, they should be of the same size. Get the input for each element of the matrix. First get elements of first matrix and then the second. Add the two matrices (i.e. add corresponding elements) and store the values in a third matrix. Display all 3 matrices.
//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 , b , c;
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) )
{
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.