Java Reference
In-Depth Information
9.2
Programs that use rectangular arrays
9.2.1
Printing a two-dimensional array
We develop a procedure to print the elements of a two-dimensional array, one
row per line. Here is its specification:
See lesson 9-23
to get the pro-
cedure to print
the array.
/** Print array d, one row per line. Precede each row by the integer
* 1 + (the row number) */
public static void printTable( int [][] d)
It makes sense to use a loop schema that processes the rows of array d , one
row at a time. So, here is a first refinement of its procedure body:
// invariant: rows 0 , ..., r-1 have been printed
for ( int r= 0; r != d.length; r= r + 1) {
Print row d[r] on one line (with its preceding integer r+1 )
}
We refine the repetend. We need a statement to print the integer r+1 , a loop
to print the elements of the row, and a statement to write a new-line character.
Again, we use a loop schema that processes an array —this time, array d[r] :
// Print row d[r] on one line (with its preceding integer r+1 )
System.out.print((1 + r) + " ");
// invariant: elements d[r][0..c-1] have been printed
for ( int c= 0; c != d[r].length; c= c + 1) {
Print d[r][c]
}
System.out.println();
Look at the argument of the statement that prints the integer r+1 . Because
the expression occurs in a place where a String value is expected, the value of
r+1 is converted to a String . Then, a String literal consisting of two blanks
/** Print array d, one row per line. Precede each row by the integer 1+( row number ) */
public static void printTable( int [][] d) {
// invariant: rows 0, …, r-1 have been printed
for ( int r= 0; r != d.length; r= r + 1) {
// Print row d[r] on one line, preceded by r+1
System.out.print((1 + r) + " ");
// invariant: d[r][0..c-1] has been printed
for ( int c= 0; c != d[r].length; c= c + 1)
{ System.out.print( " " + d[r][c]); }
System.out.println();
}
}
Figure 9.2:
A procedure to print a two-dimensional array
Search WWH ::




Custom Search