The for Loop
i = initialValue; // Initialize loop control variable while (i < endValue) { // Loop body ... i++; // Adjust loop control variable }
A for
loop can be used to simplify the preceding loop:
for (i = initialValue; i < endValue; i++) { // Loop body ... }
In general, the syntax of a for
loop is as shown below:
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; Statement(s); }
The flow chart of the for
loop is shown in Figure 4.5(a).
Figure 4.5. A for loop performs an initial action once, then repeatedly executes the statements in the loop body, and performs an action after an iteration when the loop-continuation-condition evaluates to true.
The for
loop statement starts with the keyword for, followed by a pair of parentheses enclosing initial-action,
loop-continuation-condition,
and action-after-each-iteration, and followed by the loop body enclosed inside braces. initial-action,
loop-continuation-condition,
and action-after-each-iteration
are separated by semicolons.
A for loop generally uses a variable to control how many times
the loop body is executed and when the loop terminates. This variable is
referred to as a control variable. The initial-action
often initializes a control variable, the action-after-each-iteration usually increments or decrements the control variable, and the
loop-continuation-condition tests whether the control variable has reached a
termination value. For example, the following for loop prints "Welcome
to Java!" a hundred times:
int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); }
The flow chart of the statement is shown in Figure 4.5(b). The for
loop initializes i
to 0,
then repeatedly executes the println
statement and evaluates i++
while i
is less than 100.
The initial-action,
i=0,
initializes the control variable, i.
The loop-continuation-condition,
i<
100 is a Boolean expression. The
expression is evaluated at the beginning of each iteration. If this condition is
true, execute the loop body. If it is false, the loop terminates and the program control turns to the
line following the loop.
The action-after-each-iteration,
i++, is a statement that adjusts the control variable.
This statement is executed after each iteration. It increments the control
variable. Eventually, the value of the control variable should force the loop-continuation-condition to become false. Otherwise the loop is infinite.
for (int i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); }
Tip
Note
No comments:
Post a Comment