Java Reference
In-Depth Information
In the console, there should be 10 lines with the counter (ctr) value followed by the word “little.” Please note a
couple of the
for
loop's nuances. For example, the value 1 is displayed on the first line. Even though the increment
of ctr is defined at the beginning of the loop, the increment is not performed until the end of the loop. Essentially the
increment is implemented as if it were a statement at the end of the
for
loop. Because of this, you could have specified
a pre-increment (++ctr) or post-increment (ctr++) and they both would have worked the same as ctr = ctr + 1.
The initialization (which is only performed once) and the condition check are performed before the statements
to be repeated are executed. Finally, because ctr was defined in the initialization, ctr can only be used by statements
within the
for
loop. In other words, ctr is a local variable with a
scope
of the
for
loop. If ctr was defined as a class
variable and initialized in the
for
statement, ctr would be accessible by any statement in any method in the class.
In other words, the variable would have a class
scope
.
If you were to create a flow chart for the
for
loop, it would look like Figure
7-3
.
Figure 7-3.
4.
Comment out the
for
loop and add the following while loop:
while
(ctr <= 10) {
System.out.println(ctr + " little");
}
RAD displays two errors because the variable ctr has not been defined. The
while
statement does not allow a
counter variable to be defined or initialized, therefore the counter must be defined before the
while
statement.
5.
Add the following statement before the while loop:
int
ctr = 1;