Java Reference
In-Depth Information
A
for
loop can be used to simplify the preceding loop as:
for
(i = initialValue; i < endValue; i++)
// Loop body
...
}
In general, the syntax of a
for
loop is:
for
(initial-action; loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
Statement(s);
}
for
loop
The flowchart of the
for
loop is shown in FigureĀ 5.3a.
initial-action
i = 0
loop-
continuation-
condition?
false
false
(i < 100)?
true
true
Statement(s)
(loop body)
System.out.println(
"Welcome to Java");
i++
action-after-each-iteration
(a)
(b)
F
IGURE
5.3
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 parenthe-
ses enclosing the control structure of the loop. This structure consists of
initial-action
,
loop-continuation-condition
, and
action-after-each-iteration
. The control
structure is followed by the loop body enclosed inside braces. The
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
control variable
Search WWH ::
Custom Search