90 likes | 191 Views
What output is produced by the following fragment?. int num = 1, max = 20; while (num < max) { if (num%2 == 0) System.out.println (num); num++ }. Objectives. To define and illustrate the correct syntax for the For Statement
E N D
What output is produced by the following fragment? int num = 1, max = 20; while (num < max) { if (num%2 == 0) System.out.println(num); num++ }
Objectives • To define and illustrate the correct syntax for the For Statement • To apply the For Statement in your code as part of the algorithm • Correctly analyze when to use the While Loop vs. the For Loop
The initialization is executed once before the loop begins The statement is executed until the condition becomes false Reserved word Theincrementportion is executed at the end of each iteration The condition-statement-increment cycle is executed repeatedly The for Statement • The for statement has the following syntax: for ( initialization ; condition ; increment ) statement;
The for Statement • A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }
condition evaluated true false initialization increment statement Logic of a for loop
The for Statement • Like a while loop, the condition of a for statement is tested prior to executing the loop body • Therefore, the body of a for loop will execute zero or more times • It is well suited for executing a loop a specific number of times that can be determined in advance • See Counter2.java (page 161) • See Multiples.java (page 163) • See Stars.java (page 165)
The for Statement • Each expression in the header of a for loop is optional • If the initialization is left out, no initialization is performed • If the condition is left out, it is always considered to be true, and therefore creates an infinite loop • If the increment is left out, no increment operation is performed • Both semi-colons are always required in the for loop header
Choosing a Loop Structure • When you can’t determine how many times you want to execute the loop body, use a while statement • If you can determine how many times you want to execute the loop body, use a for statement
While Loop For Loop int num = 1, max = 20; for (int num = 1; num < 20; num++) while (num < max) { { if (num%2 == 0) if (num%2 == 0) System.out.println(num); System.out.println(num); } num++ }