Program 9.4: Fill a three-dimensional array with the sum of the row and column indexes

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Program 9.4 declares, allocates and initializes a three-dimensional array. The array is filled with the sum of its indexes.

class Fill3DArray {

  public static void main (String args[]) {
    int[][][] M;
    M = new int[4][5][3];
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        for (int ver=0; ver < 3; ver++) {
          M[row][col][ver] = row+col+ver;
You need the additional nested for loop to handle the extra dimension. The syntax for still higher dimensions is similar. Just add another pair of brackets and another dimension.

Copyright 1996 Elliotte Rusty Harold
This Chapter