5.12.2 Two-Dimensional Arrays

A two-dimensional array is a grid of rows and columns. To write the type of a two-dimensional array, write two sets of empty brackets. Statement

  double[][] grid = new double[5][10];
creates an array of 5 rows and 10 columns.

To use a two-dimensional array, use grid[i][j] to indicate the variable in grid at row i, column j. Both rows and colums are numbered starting at 0.

You can also use grid[i] to indicate the entire row at index i. So


Looping through a two-dimensional array

To look at each thing in a two-dimensional array, you typically use two nested for-loops. For example, the following method writes two-dimensional array G in a grid format. It assumes that the rows and columns are filled; that is, the logical size is equal to the physical size.

  static void show(int[][] G)
  {
    for(int i = 0; i < G.length; i++)
    {
      for(int j = 0; j < G[0].length; j++)
      {
        System.out.printf("%8d", G[i][j]);
      }
      System.out.print("\n");
    }
  }

Exercises

  1. Write a statement that makes variable t be a two-dimensional array or doubles with 3 rows and 14 columns. Answer

  2. Write a static method that takes a two-dimensional array of ints as a parameter. The method should store 0 into each spot in the array. Answer