Java Reference
In-Depth Information
The call produces the following output:
[[0.0, 0.0, 0.0, 98.3, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0],
[99.4, 0.0, 0.0, 0.0, 0.0]]
Arrays can have as many dimensions as you want. For example, if you want a three-
dimensional 4 by 4 by 4 cube of integers, you would write the following line of code:
int[][][] numbers = new int[4][4][4];
The normal convention for the order of values is the plane number, followed by
the row number, followed by the column number, although you can use any conven-
tion you want as long as your code is written consistently.
Jagged Arrays
The previous examples have involved rectangular grids that have a fixed number of
rows and columns. It is also possible to create a jagged array in which the number of
columns varies from row to row.
To construct a jagged array, divide the construction into two steps: Construct the
array for holding rows first, and then construct each individual row. For example, to
construct an array that has two elements in the first row, four elements in the second
row, and three elements in the third row, you can write the following lines of code:
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];
This code would construct an array that looks like this:
[0]
[1]
[2]
[3]
[0]
0
0
jagged
[1]
0
0
0
0
[2]
0
0
0
We can explore this technique by writing a program that produces the rows of
what is known as Pascal's Triangle. The numbers in the triangle have many useful
mathematical properties. For example, row n of Pascal's triangle contains the coeffi-
cients obtained when you expand the equation:
y) n
(x
Here are the results for n between 0 and 4:
y) 0
(x
1
y) 1
(x
x
y
 
Search WWH ::




Custom Search