Java Reference
In-Depth Information
A non-Java notation for subarrays
Throughout this text, we have used the notation h..k to denote the range of
integers h , h+1 , h+2 , …, k . We can use this notation to describe a rectangular
subarray of an array b. Here are some examples:
b[0][h..k] Elements of row 0 with column numbers in h..k
b[0][h..] Elements of row 0 with column numbers at least h
b[i..j][h] Elements of column h with row numbers in i..j
b[i..j][h..k] Elements of rows i..j with column numbers
in h..k
We use this non-Java notation to provide understanding of the function in
Fig. 9.1, which sums the elements of a two-dimensional array. When reading the
outer loop, understand its repetend in terms of the statement-comment:
Add the elements of row r to x
which explains what the repetend does, not how it does it. Then, when reading
the implementation of this statement-comment, put the outer loop out of your
mind. It is possible to write the function without local variable p , using just local
variable x . We introduced p to make the function body easier to understand.
Two-dimensional array initializers
Array initializer {2, 4, 6} can be used in creating a one-dimensional array.
This notation extends to two dimensions. For example, the statement below cre-
ates and stores in c the name of a 4x3 array object —an array object that has 4
rows and 3 columns. the first row contains {2, 4, 6} , the second, {1, 1, 1} , and
so on:
int [][] c= {{2, 4, 6}, {1, 1, 1}, {4, 5, 6}, {0, 0, 1}};
/** = the sum of the elements of array b */
public static int sum( int [][] b) {
int x= 0;
// invariant: x is the sum of rows 0..r-1
for ( int r= 0; r != b.length; r= r + 1) {
// Add the elements of row r to x
int p= 0;
// invariant: p is the sum of elements b[r][0..c-1]
for ( int c= 0; c != b[r].length; c = c+1)
{ p= p + b[r, c]; }
x= x + p;
Figure 9.1:
A function to sum the elements of a two-dimensional array
Search WWH ::

Custom Search