04 Loops
04 Loops
Loops
Liang, Introduction to Java programming, 11th Edition, © 2017 Pearson Education, Inc.
All rights reserved
Opening Problem
Problem:
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
2
1
6/26/2019
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
2
6/26/2019
for Loops
for ( initial-action ;
loop-continuation-condition ;
action-after-each-iteration ) {
// loop body;
Statement(s);
}
Note
The initial-action in a for loop can be a list of zero or
more comma-separated expressions.
The action-after-each-iteration in a for loop can be a
list of zero or more comma-separated statements.
Therefore, the following two for loops are correct:
}
6
3
6/26/2019
Note
If the loop-continuation-condition in a for loop
is omitted, it is implicitly true.
Thus the statement given below in (a), which is
an infinite loop, is correct.
Caution
Adding a semicolon at the end of the for
clause before the loop body is a common
mistake, as shown below:
4
6/26/2019
Caution
Similarly, the following loop is also wrong:
int i=0; Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following
semicolon is needed to end the loop:
int i=0;
do {
System.out.println("i is " + i);
i++;
Correct
} while (i<10); 9
break
10
5
6/26/2019
continue
11
12