Two Dimensional Arrays

This chapter expands our discussion on one-dimensional arrays to two dimensional arrays. A two dimensional array is a data structure that contains a collection of cells laid out in a two dimensional grid, similar to a table with rows and columns although the values are still stored linearly in memory. Each cell in a two dimensional array can be accessed through two indexes that specify the row number and column number respectively. Like s one dimensional array, the range of each index is from zero to the size of the row or column minus one. A nested for loop is commonly used to initialize, manipulate, and access the values in a two dimensional array.

8. Different Numbers of Cells per Row


Answer:

What is the value myArray[1][2] ? 4

(Remember that array indexes start at 0 for both rows and columns.)

Different Numbers of Cells per Row

class UnevenExample
{
  public static void main( String[] arg )
  {
    // declare and construct a 2D array
    //
    int[][] uneven =  { { 1, 9, 4 },
                        { 0, 2},
                        { 0, 1, 2, 3, 4 } };

    System.out.println("uneven[0][2] is ", + uneven[0][2] ) ; // OK 
    System.out.println("uneven[1][1] is ", + uneven[1][1] ) ; // OK 
    System.out.println("uneven[1][2] is ", + uneven[1][2] ) ; // WRONG! 

    uneven[2][4] = 97;  // OK 
    uneven[1][4] = 97;  // WRONG! 

    int val = uneven[0][2] ;  // OK 
    int sum = uneven[1][2] ;  // WRONG! 
  }
}

Each row of a 2D array may have a different number of cells. In the example, the array uneven has

      • 3 cells in its first row,
      • 2 in its second row,
      • and 5 in its last row.

If a program refers to a cell that does not exist, bounds checking will catch the error (as the program runs) and generate an exception (which usually will halt your program.)

Notice that row 1 in the above has only two cells. (It is incorrect to think that row 1 has more cells but that only the first two are initialized.) Making an assignment to a cell that does not exist is an error.


Question 8:

Which of the following are correct?

  • uneven[ 0 ][ 2 ] 
  • uneven[ 1 ][ 1 ] 
  • uneven[ 2 ][ 5 ] 
  • uneven[ 3 ][ 0 ]