Java Programming: From Problem Analysis To Program Design, 3e
Java Programming: From Problem Analysis To Program Design, 3e
Java Programming: From Problem Analysis To Program Design, 3e
Chapter Objectives
Learn about repetition (looping) control structures Explore how to construct and use countcontrolled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures
Expression is always true in an infinite loop Statements must change value of expression to false
//Line 5
Output:
0 5 10 15 20
Java Programming: From Problem Analysis to Program Design, 3e 6
10
Input: first two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n)
int previous1 = Fibonacci number 1 int previous2 = Fibonacci number 2 int nthFibonacci = position of nth Fibonacci number
13
14
15
16
Example 5-9
1.
The following for loop outputs the word Hello and a star (on separate lines) five times:
for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); }
2.
19
20
23
break Statements
Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop
If condition is met, loop exited immediately
24
continue Statements
Used in while, for, and do...while structures When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/dowhile structure, expression evaluated immediately after continue statement In a for structure, the update expression is executed after the continue statement; then the loop condition executes
Java Programming: From Problem Analysis to Program Design, 3e 25
26
Output:
* ** *** **** *****
Java Programming: From Problem Analysis to Program Design, 3e 27
Chapter Summary
Looping Mechanisms
Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop EOF-controlled while loop for loop dowhile loop