Java Reference
In-Depth Information
is catenated to it, so that the row number is separated from the row elements.
Look also at the loop condition. The number of elements in row r is given
by the expression d[r].length . The expression d[0].length could also have
been used, but it is better to use d[r].length because it is correct in more sit-
uations, as we will see in Sec. 9.3.
The refinement of the statement “Print d[r][c] ” is a simple print statement
(see Fig. 9.2). A blank is printed before each array element so that the elements
are separated. This ends the development of this procedure.
Discussion
The procedure was developed in stages, using stepwise refinement (see Sec.
2.5). We first developed the outer loop, leaving its repetend as an English state-
ment. Then, we refined the repetend. While doing so, we obliterated the rest of
the program from our minds. Concentrating on one task at a time in this fashion
makes programming easier. Consciously try to separate your concerns .
9.2.2
A two-dimensional array schema
We write a program schema for processing each element of a two-dimensional
array d , where we assume that each element is processed in the same way.
If we think of processing the rows, one at a time, we begin with a for-loop
schema and write this loop:
Get the schema
from a footnote
on lesson page
9-2.
/** Process each element of d[0..][0..] */
// invariant: d[0..r-1] has been processed
for ( int r= 0; r != d.length; r= r + 1)
{ Process row r }
We then refine the repetend. Again we use a loop schema:
// Process row r
// invariant: d[r][0..c-1] has been processed
for ( int c= 0; c != d[r].length; c= c + 1)
{ Process d[r][c] }
}
This resulting schema —see Fig. 9.3 is used so often that we usually abbre-
viate it. Instead of the two invariants, we use a single invariant that contains the
// Process the elements of d[0..][0..] in row-major order .
// invariant: d[0..r-1] and d[r][0..c-1] have been processed
for ( int r= 0; r != d.length; r= r + 1)
for ( int c= 0; c != d[r].length; c= c + 1)
{ Process d[r][c] }
Figure 9.3:
A schema for processing the elements of a two-dimensional array in row-major order

Search WWH ::

Custom Search