19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.4 The for Loop 147<br />

In general, the syntax of a for loop is:<br />

for (initial-action; loop-continuation-condition;<br />

action-after-each-iteration) {<br />

// Loop body;<br />

Statement(s);<br />

}<br />

for loop<br />

The flowchart of the for loop is shown in Figure 4.3a.<br />

Initial-Action<br />

i = 0<br />

loopcontinuationcondition?<br />

false<br />

(i < 100)?<br />

false<br />

true<br />

true<br />

Statement(s)<br />

(loop body)<br />

System.out.println(<br />

"Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>");<br />

action-after-each-iteration<br />

i++<br />

(a)<br />

FIGURE 4.3 A for loop performs an initial action once, then repeatedly executes the<br />

statements in the loop body, and performs an action after an iteration when the loopcontinuation-condition<br />

evaluates <strong>to</strong> true.<br />

(b)<br />

The for loop statement starts with the keyword for, followed by a pair of parentheses<br />

enclosing the control structure of the loop. This structure consists of initial-action,<br />

loop-continuation-condition, and action-after-each-iteration. The control<br />

structure is followed by the loop body enclosed inside braces. The initial-action, loopcontinuation-condition,<br />

and action-after-each-iteration are separated by<br />

semicolons.<br />

A for loop generally uses a variable <strong>to</strong> control how many times the loop body is executed<br />

and when the loop terminates. This variable is referred <strong>to</strong> as a control variable. The initialaction<br />

often initializes a control variable, the action-after-each-iteration usually<br />

increments or decrements the control variable, and the loop-continuation-condition<br />

tests whether the control variable has reached a termination value. For example, the following<br />

for loop prints Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>! a hundred times:<br />

control variable<br />

int i;<br />

for (i = 0; i < 100; i++) {<br />

System.out.println("Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>!");<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!