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.

9. Length of a 2D Array


Answer:

int[][] uneven = 

    { { 1, 9, 4 },
      { 0, 2},
      { 0, 1, 2, 3, 4 } };

Which of the following exist?

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

Length of a 2D Array

The length of a 2D array is the number of rows it has. You might guess that "length" could be defined as a number pair (rows, columns). But the number of columns may vary from row to row so this will not work. However, the number of rows does not change so it works as a length. Here is an example program:

class UnevenExample2
{
  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("Length is: " + uneven.length );
  }
}


Question 9:

What does the program print out?