Holla Tech - Learn

Two-Dimensional Arrays

A two-dimensional array is an array of arrays and can be thought of as a table. You can also think of a two-dimensional array as a grid for representing a chess board, city blocks, and much more.

A two-dimensional array declaration indicates the number of number rows and the number of columns.
For example: 

int a[2][3]; /* A 2 x 3 array */ 

Nested curly braces are used to initialize elements row by row, as in the following statement:

int a[2][3] = {
  {3, 2, 6},
  {4, 5, 20}
}; 

The same statement can also take the form:

int a[2][3] = { {3, 2, 6}, {4, 5, 20} }; 

The former statement offers more clarity with visualizing the structure of the array.

NOTE!
An array can have more than two dimensions. For example, a[5][3][4] is an array that has 5 elements that each store 3 elements that each store 4 elements.

Accessing Two-Dimensional Arrays
 

To access an element of a two-dimensional array, both the row index and column index are required.
For example, the following statements display the value of an element and then assign a new value:

int a[2][3] = {
  {3, 2, 6},
  {4, 5, 20}
};
printf(“Element 3 in row 2 is %d\n”, a[1][2]); /* 20 */
a[1][2] = 25;
printf(“Element 3 in row 2 is %d\n”, a[1][2]); /* 25 */ 

 

Just as a for loop is used to iterate through a one-dimensional array, nested for loops are used to traverse a two-dimensional array:

int a[2][3] = {
  {3, 2, 6},
  {4, 5, 20}
};
int k, j;
/* display array contents */
for (k = 0; k < 2; k++) {
  for (j = 0; j < 3; j++) {
    printf(” %d”, a[k][j]);
  }
  printf(“\n”);

 


BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT