Java Reference
In-Depth Information
The progress is a statement that makes progress toward termination.
Generally, it increments or decrements the loop counter. Note that this statement
does not end in a semicolon.
The repetend is any statement. Almost always, we write it as a block: {…} .
Here is an example that prints the numbers 0..4 :
for (i= 0; i != 5; i= i + 1) {
Semantics of the for-loop
To show how the for-loop is executed, we give equivalent code that uses a
while-loop. First is the initialization , then the while-loop. The conditions of the
while-loop and for-loop are the same. The repetend of the while-loop consists of
the repetend of the for-loop followed by the progress part of the for-loop.
while ( condition ) {
There is one slight difference between the general for-loop and the general while-
loop when the initialization contains a declaration. The scope of a loop counter
that is declared in the for-loop is only the for-loop; in the while-loop, the scope
extends beyond the while-loop to include any statements that follow it.
Above, we wrote a for-loop that prints the numbers 0..4 . Here is the equiv-
alent while-loop:
i= 0;
while (i != 5) {
i= i + 1;
Developing a for-loop
Developing a for-loop is no different from developing a while-loop. The same
strategy is used for both. In the next development of a for-loop, we illustrate that,
in some cases, progress can be made by decrementing the loop counter.
We develop a loop to print the values 9 , 8 , and so on, down to 2 . As the first
step, we write a postcondition, which we name R .
R: 9 , 8 , , down to 2 have been printed
Search WWH ::

Custom Search