Two-Dimensional Arrays
The arrays we have discussed so far are known as one-
dimensional arrays because the data are organized
linearly in only one direction. Many applications
require that data be stored in more than one
dimension. One common example is a table, which is
an array that consists of rows and columns.
1
2
Two-Dimensional Arrays
Two-dimensional Array: a collection of a
fixed number of components arranged in
two dimensions
All components are of the same type
The syntax for declaring a two-
dimensional array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding
positive integer values
3
Accessing Array Components
The syntax to access a component of a
two-dimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer
values
indexexp1 specifies the row position and
indexexp2 specifies the column position
4
5
7
Initialization
Like one-dimensional arrays
Two-dimensional arrays can be initialized
when they are declared
To initialize a two-dimensional array when
it is declared
1. Elements of each row are enclosed within
braces and separated by commas
2. All rows are enclosed within braces
3. For number arrays, if all components of a row
are not specified, the unspecified components
are initialized to zero
8
Processing a 2-D
Array
A one-dimensional array is usually processed via a for loop. Similarly, a two-
dimensional array may be processed with a nested for loop:
for (int Row = 0; Row < NUMROWS; Row++)
{
for (int Col = 0; Col < NUMCOLS; Col++)
{
Array[Row][Col] = 0;
}
}
Each pass through the inner for loop will initialize all the elements of the current row to 0.
The outer for loop drives the inner loop to process each of the array's rows.
Initializing in
Declarations
int Array1[2][3] = { {1, 2, 3} , {4, 5, 6} };
int Array2[2][3] = { 1, 2, 3, 4, 5 };
int Array3[2][3] = { {1, 2} , {4 } };
If we printed these arrays by rows, we would find the following initializations
had taken place:
Rows of Array1:
1 2 3 for (int row = 0; row < 2; row++)
4 5 6 {
Rows of Array2: for (int col = 0; col < 3; col++)
1 2 3 {
4 5 0
scanf(“%d”,&Array1[row][col]);
Rows of Array3: }
1 2 0
4 0 0 }
Multidimensional Arrays
Multidimensional arrays can have three, four, or more
dimensions. The first dimension is called a plane,
which consists of rows and columns. The C language
considers the three-dimensional array to be an array
of two-dimensional arrays.
13
FIGURE 8-40 A Three-dimensional Array (3 x 5 x 4)
14
C View of Three-dimensional Array
15