(^224) | File Objects and Looping Statements
loopCount = 1; // Initialization
while(loopCount <= 10) // Test
{
.
. // Repeated actions
.
loopCount = loopCount + 1; // Incrementation
}
Here loopCountis the loop control variable. It is set to 1 before loop entry. The whilestate-
ment tests the expression
loopCount <= 10
and executes the loop body as long as the expression is true. The dots inside the compound
statement represent a sequence of statements to be repeated. The last statement in the loop
body increments loopCountby adding 1 to it.
Look at the statement in which we increment the loop control variable. Notice its form:
variable = variable + 1;
This statement adds 1 to the current value of the variable, and the result replaces the old value.
Variables that are used this way are called counters. In our example,loopCountis incremented
with each iteration of the loop—we use it to count the iterations. The loop control variable
of a count-controlled loop is always a counter.
We’ve encountered another way of incrementing a variable in Java. The incrementation
operator (++) increments the variable that is its operand. Thus the statement
loopCount++;
has precisely the same effect as the assignment statement
loopCount = loopCount + 1;
From here on, we will typically use the ++operator, as do most Java programmers.
When designing loops, it is the programmer’s responsibility to see that the condition to
be tested is set correctly (initialized) before the whilestatement begins. The programmer
also must make sure that the condition changes within the loop so that it eventually becomes
false; otherwise, the loop will never be exited.
loopCount = 1; // Variable loopCount must be initialized
while(loopCount <= 10)
{
.
.
.
loopCount++; // loopCount must be incremented
}