Академический Документы
Профессиональный Документы
Культура Документы
Java looping
Options
while
do-while
for
Allow programs to control how many times a statement list is
executed
Java looping
Two types of loops
Count-controlled loops
Event-controlled loops
for loop is best for count-controlled loops
while and do-while loops are for both, mainly eventcontrolled loops.
Averaging
Problem
Extract a list of positive numbers from standard input and
produce their average
Numbers are one per line
A negative number acts as a sentinel to indicate that
there are no more numbers to process
Observations
Cannot supply sufficient code using just assignments and
conditional constructs to solve the problem
Dont how big of a list to process
Need ability to repeat code as needed
Averaging
Algorithm
Prepare for processing
Get first input
While there is an input to process do {
Process current input
Get the next input
}
Perform final processing
Averaging
Problem
Extract a list of positive numbers from standard input and
produce their average
Numbers are one per line
A negative number acts as a sentinel to indicate that
there are no more numbers to process
Sample run
Enter positive numbers one per line.
Indicate end of list with a negative number.
4.5
0.5
1.3
-1
6
Average 2.1
// display result
if (valuesProcessed > 0)
// compute and display average
else
// indicate no average to display
int valuesProcessed = 0;
double valueSum = 0;
// set up the input
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
} else {
System.out.println("No list to average");
}
w h ile ( Expression
) Action
While Semantics
Expression
If Expression is
true, Action is
executed
true
Action
Expression is
evaluated at the
start of each
iteration of the
loop
false
If Expression is
false, program
execution
continues with
next statement
11
Execution Trace
valuesProcessed 3
0
1
2
int valuesProcessed = 0;
double valueSum = 0;
4.5
valueSum 6.3
0
5.0
value -1
4.5
0.5
1.3
average 2.1
if (valuesProcessed > 0) {
double average = valueSum / valuesProcessed;
System.out.println("Average: " + average);
}
else {
System.out.println("No list to average");
12
}
Loop design
Questions to consider in loop design and analysis
What initialization is necessary for the loops test
expression?
What initialization is necessary for the loops processing?
What causes the loop to terminate?
What actions should the loop perform?
What actions are necessary to prepare for the next
iteration of the loop?
What conditions are true and what conditions are false
when the loop is terminated?
13
Initialization step
is performed only
After each iteration of the
once -- just prior intcurrentTerm = 1;
body of the loop, the update
to the first
evaluation of the
for ( int i= 0; i< 5; + + i) { expression is reevaluated
test expression System .out.println(currentTerm );
currentTerm *= 2;
The body of the loop displays the
}
current term in the number series.
It then determines what is to be the
new current number in the series
14
Evaluated once
at the beginning
of the for
statements's
execution
If ForExpr is true,
Action is
executed
After the Action
has completed,
the
PostExpression
is evaluated
ForInit
ForExpr
true
Action
ForU pdate
The ForExpr is
evaluated at the
start of each
iteration of the
loop
false
If ForExpr is
false, program
execution
continues with
next statement
Logical test expression that determines whether the action and update step are
executed
Initialization step prepares for the
first evaluation of the test
expression
for ( ForInit
; ForExpression
; ForU pdate
) Action
16
17
Variable declaration
You can declare a variable in any block:
Variable n gets created
(and initialized) each time
while ( true ) {
int n = 0;
n++;
System.out.println (n);
}
System.out.println (n);
As n is not defined
here, this causes
an error
18
Variable declaration
You can declare a variable in any block:
if ( true ) {
int n = 0;
n++;
System.out.println (n);
}
System.out.println (n);
Only difference
from last slide
19
Execution Trace
i 1
0
3
2
i is 0
i is 1
i is 2
all done
20
Translates to:
int count;
count = 0;
while (count < 10) {
System.out.println (count);
count++;
}
21
int count = 0;
while (count < 10) {
System.out.println (count);
count++;
}
count IS defined here 22
Nested loops
int m = 2;
int n = 3;
for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);
for (int j = 0; j < m; ++j) {
System.out.println("
j is "
}
i is 0
}
j is
j is
i is 1
j is
j is
i is 2
j is
j is
+ j);
0
1
0
1
0
1
24
Nested loops
int m = 2;
int n = 4;
for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);
for (int j = 0; j < i; ++j) {
System.out.println("
j is " + j);
}
}
i is 0
i is 1
j is
i is 2
j is
j is
i is 3
j is
j is
j is
25
0
0
1
0
1
2
3.
4.
5.
Action
true
Expression
false
27
28
Guessing a number
This program will allow the user to guess the number the
computer has thought of
Main code block:
do {
System.out.print ("Enter your guess: ");
guessedNumber = stdin.nextInt();
count++;
} while ( guessedNumber != theNumber );
29
never executed
executed once
30
The continue keyword will immediately start the next iteration of the
loop
The rest of the current loop is not executed
But the ForUpdate part is, if continue is in a for loop
for ( int a = 0; a <= 10; a++ ) {
if ( a % 2 == 0 ) {
continue;
}
System.out.println (a + " is odd");
}
Output:1
3
5
7
9
is
is
is
is
is
odd
odd
odd
odd
odd
31
The break keyword will immediately stop the execution of the loop
Execution resumes after the end of the loop
for ( int a = 0; a <= 10; a++ ) {
if ( a == 5 ) {
break;
}
System.out.println (a + " is less than five");
}
Output:0
1
2
3
4
is
is
is
is
is
less
less
less
less
less
than
than
than
than
than
five
five
five
five
five
32