Chapter 5: Repetition Control Structures

Transcription

Chapter 5: Repetition Control Structures
Chapter 5:
Repetition Control Structures
ΠRepetition (looping) control structures.
ΠCount-controlled, sentinel-controlled, flagcontrolled, and EOF-controlled repetition
structures.
ΠBreak and continue statements.
Πnested control structures.
Java Programming: From Problem Analysis to Program Design, Second Edition
1
Why Is Repetition Needed?
ΠThere are many situations in which the same
statements need to be executed several times.
ΠExample:
ΠFormulas used to find average grades for
students in a class.
Java Programming: From Problem Analysis to Program Design, Second Edition
2
1
The while Looping (Repetition) Structure
ΠSyntax:
while (expression)
statement
ΠExpression is always true in an infinite loop.
ΠStatements must change value of expression to false.
Java Programming: From Problem Analysis to Program Design, Second Edition
3
The while Looping (Repetition) Structure
Example 5-1
i = 0;
while (i <= 20)
{
System.out.print(i + " ");
i = i + 5;
}
System.out.println();
//Line 1
//Line 2
//Line 3
//Line 4
//Line 5
Output
0 5 10 15 20
Java Programming: From Problem Analysis to Program Design, Second Edition
4
2
The while Looping (Repetition) Structure
Typically, while loops are written in the following form:
//initialize the loop control variable(s)
while (expression)
//expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}
Java Programming: From Problem Analysis to Program Design, Second Edition
5
Counter-Controlled while Loop
ΠUsed when exact number of data or entry pieces is
known.
ΠGeneral form:
int N = //value input by user or specified
//in program
int counter = 0;
while (counter < N)
{
.
.
.
counter++;
.
.
.
}
Java Programming: From Problem Analysis to Program Design, Second Edition
6
3
Sentinel-Controlled while Loop
ΠUsed when exact number of entry pieces is unknown, but
last entry (special/sentinel value) is known.
ΠGeneral form:
Input the first data item into variable;
while (variable != sentinel)
{
.
.
.
input a data item into variable;
.
.
.
}
Java Programming: From Problem Analysis to Program Design, Second Edition
7
Flag-Controlled while Loop
ΠBoolean value used to control loop.
ΠGeneral form:
boolean found = false;
while (!found)
{
.
.
.
if (expression)
found = true;
.
.
.
}
Java Programming: From Problem Analysis to Program Design, Second Edition
8
4
EOF(End of File)-Controlled while Loop
ΠUsed when input is from files.
ΠSentinel value is not always appropriate.
ΠIn an EOF-controlled while loop that uses the Scanner
object console to input data, console acts at the
loop control variable.
ΠThe method hasNext, of the class Scanner,
returns true if there is an input in the input stream;
otherwise, it returns false.
ΠThe expression console.hasNext() acts as the
loop condition.
ΠExpressions such as console.nextInt() update the
value of the loop condition.
Java Programming: From Problem Analysis to Program Design, Second Edition
9
EOF-Controlled while Loop
ΠA general form of the EOF-controlled while loop
that uses the Scanner object console to input
data is:
while (console.hasNext())
{
//Get the next input and store in an
//appropriate variable
//Process data
}
Java Programming: From Problem Analysis to Program Design, Second Edition
10
5
EOF-Controlled while Loop
ΠSuppose that inFile is a Scanner object
initialized to the input file. In this case, the EOFcontrolled while loop takes the following form:
while (inFile.hasNext())
{
//Get the next input and store in an
//appropriate variable
//Process data
}
Java Programming: From Problem Analysis to Program Design, Second Edition
11
Programming Example: Checking
Account Balance
Œ Input file: Customer’s account number, account
balance at beginning of month, transaction type
(withdrawal, deposit, interest), transaction amount.
ΠOutput: Account number, beginning balance, ending
balance, total interest paid, total amount deposited,
number of deposits, total amount withdrawn,
number of withdrawals.
Java Programming: From Problem Analysis to Program Design, Second Edition
12
6
Programming Example: Checking
Account Balance
ΠSolution:
Œ
Œ
Œ
Œ
Read data.
EOF-controlled loop.
switch structure of transaction types.
Determine action (add to balance or subtract
from balance depending on transaction type).
Java Programming: From Problem Analysis to Program Design, Second Edition
13
Programming Example:
Fibonacci Number
Œ
Fibonacci formula for any Fibonacci sequence:
an = an-1 + an-2
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
Output: nth Fibonacci number.
Java Programming: From Problem Analysis to Program Design, Second Edition
14
7
Programming Example: Fibonacci Number (Solution)
if (nthFibonacci == 1)
current = previous1;
else if (nthFibonacci == 2)
current = previous2;
else
{
counter = 3;
while (counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
}
ΠFinal result found in last value of current.
Java Programming: From Problem Analysis to Program Design, Second Edition
15
The for Looping (Repetition) Structure
ΠSpecialized form of while loop.
ΠSimplifies the writing of count-controlled loops.
ΠSyntax:
for (initial statement; loop condition;
update statement)
statement
Java Programming: From Problem Analysis to Program Design, Second Edition
16
8
The for Looping (Repetition) Structure
ΠExecution:
ΠInitial statement executes.
ΠLoop condition is evaluated.
ΠIf loop condition evaluates to true, execute for
loop statement and execute update statement.
ΠRepeat until loop condition is false.
Java Programming: From Problem Analysis to Program Design, Second Edition
17
The for Looping (Repetition) Structure
Example 5-8
The following for loop prints the first 10
nonnegative integers:
for (i = 0; i < 10; i++)
System.out.print(i + " ");
System.out.println();
Java Programming: From Problem Analysis to Program Design, Second Edition
18
9
The for Looping (Repetition) Structure
Example 5-9
1. The following for loop outputs the word Hello and a star (on
separate lines) five times:
2.
for (i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
The following for loop outputs the word Hello five times and the
star only once:
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
Java Programming: From Problem Analysis to Program Design, Second Edition
19
The for Looping (Repetition) Structure
ΠDoes not execute if initial condition is false.
ΠUpdate expression changes value of loop control
variable, eventually making it false.
ΠIf loop condition is always true, result is an infinite
loop.
ΠInfinite loop can be specified by omitting all three
control statements.
ΠIf loop condition is omitted, it is assumed to be
true.
Πfor statement ending in semicolon is empty.
Java Programming: From Problem Analysis to Program Design, Second Edition
20
10
Programming Example: Classify
Numbers
ΠInput: N integers (positive, negative, and zeros).
int N = 20;
//N easily modified
ΠOutput: Number of 0s, number of even integers,
number of odd integers.
Java Programming: From Problem Analysis to Program Design, Second Edition
21
Programming Example: Classify Numbers
(Solution)
for (counter = 1; counter <= N; counter++)
{
number = console.nextInt();
System.out.print(number + " ");
switch (number % 2)
{
case 0: evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1: odds++;
} //end switch
} //end for loop
Java Programming: From Problem Analysis to Program Design, Second Edition
22
11
The do…while Loop (Repetition)
Structure
ΠSyntax:
do
statement
while (expression);
ΠStatements are executed first and then expression is
evaluated.
ΠStatements are executed at least once and then
continued if expression is true.
Java Programming: From Problem Analysis to Program Design, Second Edition
23
do…while Loop (Post-Test Loop)
Java Programming: From Problem Analysis to Program Design, Second Edition
24
12
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 is exited immediately.
Java Programming: From Problem Analysis to Program Design, Second Edition
25
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/do…while structure,
expression is evaluated immediately after continue
statement.
ΠIn a for structure, the update statement is executed
after the continue statement; the loop condition
then executes.
Java Programming: From Problem Analysis to Program Design, Second Edition
26
13
Nested Control Structures
ΠProvides new power, subtlety, and complexity.
Œ if, if…else, and switch structures can be
placed within while loops.
Πfor loops can be found within other for loops.
Java Programming: From Problem Analysis to Program Design, Second Edition
27
Nested Control Structures (Example)
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
Output:
*
**
***
****
*****
Java Programming: From Problem Analysis to Program Design, Second Edition
28
14
Chapter Summary
ΠLooping mechanisms:
Œ
Œ
Œ
Œ
Œ
Œ
Counter-controlled while loop
Sentinel-controlled while loop
Flag-controlled while loop
EOF-controlled while loop
for loop
do…while loop
Πbreak statements
Πcontinue statements
ΠNested control structures
Java Programming: From Problem Analysis to Program Design, Second Edition
29
15