Declaring Two-Dimensional Arrays in C++ 330

An element in a two-dimensional array is accessed through a row and column index.

The syntax for declaring a two-dimensional array is

elementType arrayName[ROW_SIZE][COLUMN_SIZE];

As an example, here is how to declare a two-dimensional array matrix of int values:

int matrix[5][5];

Two subscripts are used in a two-dimensional array, one for the row and the other for the column. As in a one-dimensional array, the index for each subscript is of the int type and starts from 0, as shown in Figure 8.1a.

To assign the value 7 to a specific element at row 2 and column 1, as shown in Figure 8.1b, you can use the following:

matrix[2][1] = 7;

You also can use an array initializer to declare and initialize a two-dimensional array. For example, the code in (a) below declares an array with the specified initial values, as shown in Figure 8.1c. This is equivalent to the code in (b).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *