Topic 11: Two-Dimensional Array

A two-dimensional array can be visualized as a table in that the variables are in rows and columns. Each variable in a two-dimensional array is identified by a unique combination of two subscripts specifying the variable’s row and column position. The number of variables in a two-dimensional array can be determined by multiplying the number of rows by the number of columns.

Variables located in the first, second, etc. row of a two-dimensional array are assigned a row subscript of 0, 1, etc. Similarly, variables located in the first, second, etc. column of a two-dimensional array are assigned a column subscript of 0, 1, etc.

Example
  • ...
    Figure 11.1

The variable in a two-dimensional array can be referred to by the array’s name immediately followed by the variable’s row and column subscripts (in that order), each enclosed in its own set of square brackets.

As with one-dimensional arrays, the last row and column subscripts of a two-dimensional array will always be one less than the number of rows and columns (respectively) in the array, since the subscripts begin at 0.

Syntax for declaring a two-dimensional array:
dataType arrayName [numberOfRows][numberOfColumns] = {{initialValues}, {initialValues }, …{initialValues }};
  • dataType specifies the data type of elements in the array (all elements must have same data type)
  • numberOfRows and numberOfColumns specify number of rows and columns in array, respectively
  • You initialize elements in a two-dimensional array by entering a separate initialValues section, enclosed in braces, for each row of the array
  • Maximum number of initialValues sections you may enter is the number of rows in the array
  • Within individual initialValues sections, you enter one or more values separated by commas
  • Maximum number of values you may enter in a row is the number of columns
Example
  • int[][] oddNumbers = { {1, 3, 5, 7}, {9, 11, 13, 15} };

Displaying the Contents of a Two-Dimensional Array

To display the contents of a two-dimensional array, you must access its individual elements. Two counter-controlled loops can be used; one to keep track of the row subscript and the other to keep track of the column subscript

Example: print out all the items in the oddNumbers array
  • ...
    Figure 10.2
Output
  • 1 3 5 7 9 11 13 15 17 19 21 23