Java For Android: Indefinite Loops: Julie L. Johnson
Java For Android: Indefinite Loops: Julie L. Johnson
Indefinite Loops
Julie L. Johnson
[email protected]
Java for Android
What if?
• What if I want to continually reduce some number n by 3
until the number is less than 19? How many times should
my loop execute?
2
Java for Android
a loop that can run indefinitely
test false
true
executable executable
statements statements
3
Java for Android
the while loop: syntax
while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s); false
test
}
true
statements statements
4
Java for Android
the while loop: an example
5
Java for Android
the while loop and the for loop
The while loop can do all that the for loop can do
6
Java for Android
the while loop and the for loop
The for loop can do all that the while loop can do
but in a very clumsy way
7
Java for Android
Adopt the practice of using a while loop when the
number of iterations is not known before you begin
• an indefinite loop
false
• best used when the number test
of iteration is unknown true
executable executable
statements statements
8
Java for Android
Notice that the syntax is similar to an if statement
but the result is very different!
int total = 0; int total = 0;
if (total < 5) while (total < 5){
total = total + cost; total = total + cost;
} }
true true
total = total =
total + cost total + cost
9
Java for Android
while loops are useful when testing user input
10
Java for Android
11
Java for Android
the do while loop
statement
• an indefinite loop
true
• best used when the number test
of iteration is unknown
• use when you will execute false
the loop at least once
12
Java for Android
the do while loop: syntax
do while loop: executes its body and continues doing so as
long as a logical test is true.
do { statement
statement(s);
true
}while (test) ;
test
false
13
Java for Android
The do while loop: an example
if (num > 3){
i = 1;
Out.print(“Positive multiples of 3 less than the input”);
do{
Out.print(3*i);
statement
Out.print(“ ”);
i++; statement
}while (3*i < num);
true
}
test
false
14
Java for Android
indefinite loop constructs
false statement
test
true true
statements test
false
statements
statements
15