09.
Flow of Control:
Loops
[ECE20016/ITP20003] Java Programming
Handong Global University
Agenda
■ Java Loop Statements
■ Programming with Loops
Handong Global University
Java Loop Statements
■ A portion of a program that repeats a
statement or a group of statements is called a
loop.
■ The statement or group of statements to
be repeated is called the body of the loop.
Handong Global University
Java Loop Statements
■ The while statement
■ The do-while
statement
■ The for Statement
Handong Global University
The while
Statement
■ Also called a while loop
■ A while statement repeats while a
controlling boolean expression remains true
■ The loop body typically contains an action that
ultimately causes the controlling boolean
expression to become false.
Handong Global University
WhileDemo
import java.util.Scanner;
public class
WhileDemo
{
public static void
main (String [] args)
{
int count, number;
System.out.println ("Enter a number");
Scanner keyboard = new Scanner
(System.in); number = keyboard.nextInt ();
count = 1; // loop variable
while (count <= number) //
control expression
{
System.out.print (count + ", ");
count++; //
sometimes, makes ‘count <= number’ false
}
System.out.println ();
System.out.println ("Buckle my
shoe.");
}
}
Handong Global University
The while Statement
Handong Global University
WrileDemo
■ Result
Handong Global University
The while Statement
■ Syntax
while (Boolean_Expression)
Body_Statement
Or
while (Boolean_Expression)
{
First_Statement
Second_Statement
…
}
Handong Global University
The do-while Statement
■ Also called a do-while loop
■ Similar to a while statement, except that the loop body is
executed at least once
■ Syntax
do
Body_Statement
while (Boolean_Expression);
■ Don’t forget the semicolon!
Handong Global University
DoWhileDemo
import java.util.Scanner;
public class DoWhileDemo
{
public static void main
(String [] args)
{
int count, number;
System.out.println ("Enter a number");
Scanner keyboard = new Scanner
(System.in); number = keyboard.nextInt ();
count = 1;
do
{
System.out.print (count + ", ");
count++;
}
while (count <= number);
System.out.println ();
System.out.println ("Buckle my
shoe.");
}
}
Handong Global University
DoWhileDemo
■ Result
Handong Global University
The do-while Statement
Handong Global University
The do-while
Statement
■ First, the loop body is
executed.
■ Then the boolean expression is
checked.
■ As long as it is true, the loop is
executed again.
■ If it is false, the loop is exited.
■ Equivalent while
statement
Statement(s)_S1
while (Boolean_Condition)
Statement(s)_S1
Handong Global University
Programming Example:
Bug Infestation
■ Given
■ Volume a roach: 0.002 cubic feet
■ Starting roach population
■ Rate of increase: 95%/week
■ Volume of a house
■ Find
■ Number of weeks to exceed the capacity of the house
■ Number and volume of roaches
Handong Global University
Programming Example:
Bug Infestation
■ Algorithm for roach population program
(rough draft)
1. Get volume of house.
2. Get initial number of roaches in house.
3. Compute number of weeks until the house
is full of roaches.
4. Display results.
Handong Global University
Programming Example:
Bug Infestation
■ Variables needed
■ GROWTH_RATE —weekly growth rate of the roach population
(a constant 0.95)
■ ONE_BUG_VOLUME —volume of an average roach (a
constant 0.002)
■ houseVolume — volume of the house
■ startPopulation —initial number of roaches
■ countWeeks —week counter
■ population —current number of roaches
■ totalBugVolume —total volume of all the roaches
■ newBugs —number of roaches hatched this week
■ newBugVolume —volume of new roaches
Handong Global University
Detailed Algorithm
■ Algorithm for roach population program
1. Read houseVolume
2. Read startPopulation
3. population = startPopulation
4. totalBugVolume = population * ONE_BUG_VOLUME
5. countWeeks = 0
6. while (totalBugVolume < houseVolume)
{
newBugs = population * GROWTH_RATE
newBugVolume = newBugs * ONE_BUG_VOLUME
population = population + newBugs
totalBugVolume = totalBugVolume + newBugVolume
countWeeks = countWeeks + 1
}
7. Display startPopulation, houseVolume, countWeeks, population, and
totalBugVolume
Handong Global University
Programming Example:
Bug Infestation
■ Result
Handong Global University
Infinite Loops
■ A loop which repeats without ever ending
is called an infinite loop.
■ If the controlling boolean expression never becomes false, a
while loop or a do-while loop will repeat without
ending. Ex) A negative growth rate in the preceding problem
causes
totalBugVolume always to be less than houseVolume
Handong Global University
Nested Loops
■ The body of a loop can contain any kind
of statements, including another loop.
// an outer loop
while (Boolean_Expression){
[statements…]
// a loop in an outer loop
// a nested loop or an inner loop
while(Boolean_Expression) {
[statements…]
}
}
Handong Global University
The for Statement
■ A for statement executes the body of a loop a
fixed number of times.
■ Syntax
for(Initialization; Condition; Update)
Body_Statement
□ Body_Statement can
be either a simple statement or a
compound statement.
Ex) for (count = 1; count < 3; count++)
System.out.println(count);
■ Corresponding while statement
Initialization
while (Condition)
Body_Statement_Including_Updat
e
Handong Global University
The for Statement
Handong Global University
ForDemo
public class ForDemo
{
public static void main (String [] args)
{
int countDown;
for (countDown = 3 ; countDown >= 0 ; countDown--)
{ System.out.println (countDown);
System.out.println ("and counting.");
}
System.out.println ("Blast off!");
}
}
Handong Global University
The for Statement
Handong Global University
The for Statement
■ Possible to declare variables within a for statement
int sum = 0;
for (int n = 1; n <= 10; n++)
sum = sum + n * n;
■ Note that variable n is
local to the loop
Handong Global University
The for Statement
■ A comma separates multiple initializations
for (n = 1, product = 1; n <= 10; n++)
product = product * n;
■ Only one boolean expression is allowed, but it can
consist of &&s, ||s, and !s.
■ Multiple update actions are allowed, too.
for (n = 1, product = 1; n <= 10; product = product * n, n+
+);
Handong Global University
The for-each Statement
■ Possible to step through values of an enumeration type
■ Example
enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}
for (Suit nextSuit : Suit.values())
System.out.print(nextSuit + " ");
System.out.println();
Handong Global University
Agenda
■ Java Loop Statements
■ Programming with Loops
Handong Global University
The Loop Body
■ To design the loop body, write out the actions
the code must accomplish.
Ex) Read numbers from the user and compute the sum of
them
Handong Global University
The Loop Body
■ Then, look for a repeated pattern.
■ The repeated pattern will form the body of the loop.
Handong Global University
Initializing Statements
■ Some variables need to have a value before the
loop begins.
■ Other variables get values only while the loop is
iterating.
Handong Global University
Controlling
Number of Loop Iterations
■ If the number of iterations is known before the loop
starts, the loop is called a count-controlled loop.
■ Use a for loop.
■ Asking the user before each iteration if it is time to end
the loop is called the ask-before-iterating technique.
■ Appropriate for a small number of iterations
■ Use a while loop or a do-while loop.
Handong Global University
Controlling
Number of Loop Iterations
■ For large input lists, a sentinel value can be
used to signal the end of the list.
■ The sentinel value must be different from all the other possible
inputs.
■ A negative number following a long list of nonnegative exam
scores could be suitable.
90
0
10
-1
Handong Global University
Controlling
Number of Loop Iterations
Ex) Reading a list of scores followed by a sentinel value
int next = keyboard.nextInt();
while (next >= 0)
{
Process_The_Score
next =
keyboard.nextInt();
}
Handong Global University
BooleanDemo
import java.util.Scanner;
public class BooleanDemo
{
public static void main
(String [] args)
{
System.out.println ("Enter nonnegative numbers.");
System.out.println ("Place a negative number at the end");
System.out.println ("to serve as an end marker.");
int sum = 0;
boolean areMore = true;
Scanner keyboard = new Scanner (System.in);
while (areMore)
{
int next = keyboard.nextInt ();
if (next < 0)
areMore = false;
else
sum = sum +
next;
}
System.out.println
("The sum of the
numbers is " + sum);
}
}
Handong Global University
BooleanDemo
■ Result
Handong Global University
The break Statement in Loops
■ A break statement can be used to end a
loop immediately.
■ The break statement ends only the innermost loop or
switch statement that contains the break statement.
■ Use break statements sparingly (if ever).
■ break statements make loops more difficult to understand.
Handong Global University
The break Statement in Loops
■ Note program fragment, ending a loop with a break
statement,
Handong Global University
The continue Statement in Loops
■ A continue statement
■ Ends current loop iteration
■ Begins the next one
■ Text recommends avoiding use
■ Introduce unneeded complications
Handong Global University
Tracing Variables
■ Tracing variables means watching the variables change
while the program is running.
■ Simply insert temporary output statements in your program to
print of the values of variables of interest
■ Or, learn to use the debugging facility (debugger) that may be
provided by your system.
Handong Global University
Loop Bugs
■ Common loop bugs
■ Unintended infinite loops
■ Off-by-one errors
■ Testing equality of floating-point numbers
■ Subtle infinite loops
■ The loop may terminate for some input values, but not for
others.
Ex) You can’t get out of debt when the monthly penalty exceeds the
monthly payment.
Handong Global University