Page 163 - Introduction to Programming with Java: A Problem Solving Approach
P. 163

                {
}
System.out.print(i + " ");
System.out.println("Liftoff!");
Apago PDF Enhancer
Figure 4.14 shows the for loop’s syntax and semantics. The for loop header does a lot of work. So much work that it’s split into three components—the initialization, condition, and update components. The fol- lowing list explains how the for loop uses the three components. As you read the list, refer to Figure 4.14’s flowchart to get a better idea of what’s going on.
1. Initialization component
Before the first pass through the body of the loop, execute the initialization component.
2. Condition component
Before each loop iteration, evaluate the condition component:
• If the condition is true, execute the body of the loop.
• If the condition is false, terminate the loop (exit to the statement below the loop’s closing brace).
3. Update component
After each pass through the body of the loop, return to the loop header and execute the update compo- nent. Then, recheck the continuation condition in the second component, and if it’s satisfied, go through the body of the loop again.
Countdown Example
Here is a code fragment for the countdown example mentioned at the start of this section:
for (int i=10; i>0; i--)
4.10 for Loop 129
 for (<initialization>; <condition>; <update>)
{
    false
<initialization>
<condition> true
<statement(s)>
<update>
   }
<statement(s)>
Figure 4.14 Syntax and semantics for the for loop
The *’s indicate that count - 1 multiplications are necessary. So count factorial requires count - 1
loop iterations. Since you know the number of iterations for the loop (count - 1), use a for loop. Syntax and Semantics





































































   161   162   163   164   165