Loops: Kevin Sahr, PHD
Loops: Kevin Sahr, PHD
Loops
we saw that the flow of control can be changed
using conditional statements
allow our program to choose which statement to execute
next
1-
1-
1-
Types of Loops
the 3 Java loops are:
1. while loops
2. for loops (will discuss later)
3. do-while loops (will discuss later)
The While-Loop
boolean
expression
syntax:
while (condition)
statement;
1-
1-
1-
condition
evaluated
true
false
statement
Common Uses
here are some common loop uses:
1. input validation
2. counter-controlled loops
3. sentinel loops
Input Validation
we have used if-statements to validate input to check if
an input value is valid
EX:
double width;
width = Input.readDouble(Enter width: );
if (width <= 0.0)
{
Output.showMessage(NEGATIVE WIDTH);
System.exit(0);
}
double width;
width = Input.readDouble(Enter width: );
while (width <= 0.0)
width = Input.readDouble(negative width +
width + entered; enter a positive width: );
1-
10
1-
11
1-
12
Counter-Controlled Loops
a counter-controlled loop repeats a task a specified
number of times
implements the algorithm:
1-
13
EX abstract pseudocode:
int count = 0;
while (count < numCats)
{
Output.showMessage(another cat);
count = count + 1;
} // while
14
14
15
1-
16
Infinite Loops
since a while-loop will continue looping until the
condition becomes false the loop must contain
statements that change the condition value
if the condition never becomes false, the loop is
an infinite loop that will never terminate
if this happens, click on the JGrasp End button (to
the left of the output window)
1-
17
1-
18
1-
19
1-
20
Sentinel Loops
a sentinel loop gets input values from the user until
the sentinel value is input
the sentinel value is a special input value that
represents the end of input
pseudocode:
input value
while value is not equal to the sentinel value
do the task with value
input value
Arbitrary Loops
loops dont need to follow these common patterns
to write a loop for a particular problem you must
answer three questions:
1. what task(s) will be performed each time the loop
executes?
2. what will be true if the loop should execute again?
1-
21
1-
22
1-
23
1-
24
the tuition amount will be less than twice the original tuition
amount
Lecture 18 Vocabulary
loop
while-loop
input validation
counter-controlled loops
infinite loops
sentinel loop
sentinel value