Two-dimensional array
The following program numbers each element in the array from top to bottom, left to right, and then shows these values:
/ / Demonstrate a two dimensional array.
class TwoDArray {
public static void main (String args [ ] ) {
int two D [ ] = new int [4] [5] ;
int i,j, k = 0;
for (i=0; i<4; i+ +)
for (j=0; j<5; j + +) { twoD[i] [j] = K;
K + +;
}
for (i=0; i<4; i+ +) {
for (j=0; j<5; j ++ )
system.out.print (twoD[i] [j] + " ") ;
system.out.println ( );
}
}
}
This program generates the given output.
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you require only specify the memory for first (leftmost) dimension. You could allocate the remaining dimensions separately. For instance, this given code allocates memory for the first dimension of twoD whenever it is declared. That allocates the second dimension manually.
int twoD [ ] [ ] = new int [4] [ ];
twoD[0] = new int [5];
twoD[1] = new int [5];
twoD[2] = new int [5];
twoD[3] = new int [5];