Program 9.2: Fill a Two-Dimensional Array with the sum of the row and column indexes

Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However you have to specify two dimensions rather than one, and you typically use two nested for loops to fill the array. The array examples above were filled with the sum of their row and column indices. Program 9.2 creates and fills such an array.

class FillArray {

  public static void main (String args[]) {
  
    int[][] M;
    M = new int[4][5];
  
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        M[row][col] = row+col;
      }
    }
    
  }
  
}

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home