Java Lecture 1-5
Java Lecture 1-5
Loops
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
1
Objectives
To write programs for executing statements repeatedly using a while loop (§5.2).
To develop a program for GuessNumber and SubtractionQuizLoop (§5.2.1).
To follow the loop design strategy to develop loops (§5.2.2).
To develop a program for SubtractionQuizLoop (§5.2.3).
To control a loop with a sentinel value (§5.2.3).
To obtain large input from a file using input redirection rather than typing from the
keyboard (§5.2.4).
To write loops using do-while statements (§5.3).
To write loops using for statements (§5.4).
To discover the similarities and differences of three types of loop statements (§5.5).
To write nested loops (§5.6).
To learn the techniques for minimizing numerical errors (§5.7).
To learn loops from a variety of examples (GCD, FutureTuition,
MonteCarloSimulation) (§5.8).
To implement program control with break and continue (§5.9).
(GUI) To control a loop with a confirmation dialog (§5.10).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
2
Program Execution Structure
Compiler executes in three different ways:
Process 2
Process 3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Motivations
Suppose that you need to print a string
(e.g., "Welcome to Java!") a hundred times.
It would be tedious to have to write the following
statement a hundred times:
System.out.println("Welcome to Java!");
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Java Loops – while, do…While, & for
There may be a situation when we need to
execute a block of code several number of
times, and is often referred to as a loop.
Java has very flexible three looping
mechanisms. You can use one of the
following three loops:
while Loop
do...while Loop
for Loop
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
Opening Problem
Problem:
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
while Loop
Use a loop statement if you need to do the same
thing repeatedly.
pseudocode syntax Java syntax
while (<condition>)
while <condition>
{
<statement(s)> <statement(s)>
}
The condition is at the bottom of the loop (in contrast to the
while loop, where the condition is at the top of the loop).
The compiler requires putting a ";" at the very end, after the do
loop's condition.
Proper style dictates putting the "while" part on the same line as
the "}" Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
7
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} // end of while } // end of while
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8
while Loop
A while loop is a control structure that allows you to repeat a task
a certain number of times.
Using loop statement means tell the computer to print a string a
hundred times without coding:
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
} // end of while
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
} // end of while
} // end of main method
} // end of class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
9
Here key point of the while loop is that the loop might not ever
run. When the expression is tested and the result is false, the loop
body will be skipped and the first statement after the while loop will
be executed. Syntax
while(Boolean_expression)
{ //Statements
}
Example:
public class Test1 {
public static void main(String args[]){
int x= 10;
while( x < 20 ){
System.out.print("value of x :" + x);
x++;
System.out.print("\n");
} //end of while
} // end of main
} //end Liang,
ofIntroduction
class to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
10
while Loop
Write a main method that finds the sum of user-
entered integers where -99999 is a sentinel value.
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int sum = 0; // sum of user-entered values
int x; // a user-entered value
System.out.print("Enter an integer (-99999 to quit): ");
x = stdIn.nextInt();
while (x != -99999)
{
sum = sum + x;
System.out.print("Enter an integer (-99999 to quit): ");
x = stdIn.nextInt();
} // end of while
System.out.println("The sum is " + sum);
} // end main
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
import java.util.Scanner;
public class SentinelValue {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Read an initial data
System.out.print(
"Enter an int value (the program exits if the input is 0): ");
int data = input.nextInt();
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
12
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
13
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
16
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
19
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
20
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
Caution
Don’t use floating-point values for equality checking in a loop control.
Since floating-point values are approximations for some values, using
them could result in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
Variable item starts with 1 and is reduced by 0.1 every time the loop
body is executed. The loop should terminate when item becomes 0.
However, there is no guarantee that item will be exactly 0, because the
floating-point arithmetic is approximated. This loop seems OK on the
surface, but it is actually an infinite loop.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22
do-while Loop
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
do While Loop
When to use a do loop:
– If you know that the repeated thing will
always have to be done at least one time.
Syntax:
do
{
<statement(s)>
} while (<condition>);
Initial-Action i=0
Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
27
for Loop
When to use a for loop:
– If you know the exact number of loop iterations
before the loop begins.
For example, use a for loop to:
– Print this countdown from 10.
Sample session:
10 9 8 7 6 5 4 3 2 1 Liftoff!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
28
for Loop
for loop syntax for loop example
for (<initialization>; for (int i=10; i>0; i--)
<condition>; <update>) {
{ System.out.print(i + " ");
<statement(s)> }
} System.out.println("Liftoff!");
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
30
The for loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
A for loop is useful when you know how many times a task is to be
repeated.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
31
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables.
for(int x = 10; x<20; x = x + 1);
Next, the Boolean expression is evaluated. If it is true, the body of
the loop is executed.
x < 20; // true, then
System.out.print("value of x : " + x ); // body of the loop
System.out.print("\n"); //body of the for loop
// increment the statement and back to checking the condition
If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back
up to the update statement.
The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats itself (body of loop, then update step,then
Boolean expression). After the Boolean expression is false, the for loop
terminates. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
For Loop vs. While Loop
The only thing that can make it faster would be to have less nesting
of loops, and looping over less values.
The only difference between a for loop and a while loop is the
syntax for defining them. There is no performance difference at all.
int i = 0;
while (i < 20){
// do stuff
i++;
}
Is the same as:
for (int i = 0; i < 20; i++){
// do Stuff
}
(Actually the for-loop is a little better because the i will be out of scope
after the loop while the i will stick around in the while loop case.)
A for loop is just a syntactically prettier way of looping
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
33
Problem: Guessing Numbers
Write a program that randomly generates an
integer between 0 and 100, inclusive. The program
prompts the user to enter a number continuously
until the number matches the randomly generated
number. For each user input, the program tells the
user whether the input is too low or too high, so
the user can choose the next input intelligently.
Here is a video and sample run:
Video Link: Problem Guessing Numbers GuessNumber
Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
34
import java.util.Scanner;
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
} Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
35
rights reserved. 0132130807
}
Problem: An Advanced Math Learning Tool
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
36
import java.util.Scanner;
public class SubtractionQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; // Number of questions
int correctCount = 0; // Count the number of correct answers
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = ""; // output string is initially empty
Scanner input = new Scanner(System.in);
}
((number1 - number2 == answer) ? " correct" : " wrong");
SubtractionQuizLoop
long endTime = System.currentTimeMillis();
long testTime = endTime - startTime;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
42
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
44
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
45
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
46
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
47
animation
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
48
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
50
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
51
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
52
For Loop vs. While Loop
The only thing that can make it faster would be to have less nesting
of loops, and looping over less values.
The only difference between a for loop and a while loop is the
syntax for defining them. There is no performance difference at all.
int i = 0;
while (i < 20){
// do stuff
i++;
}
Is the same as:
for (int i = 0; i < 20; i++){
// do Stuff
}
(Actually the for-loop is a little better because the i will be out of scope
after the loop while the i will stick around in the while loop case.)
A for loop is just a syntactically prettier way of looping
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
53
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; ) {
// Loop body // Loop body
} }
(a) (b)
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
54
Recommendations
Use the one that is most intuitive and comfortable for
you.
o In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times.
o A while loop may be used if the number of repetitions
is not known, as in the case of reading the numbers until
the input is 0 (use counter).
o A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
55
Loop Comparison
for loop: When to use Template
If you know, prior to for (int i=0; i<max; i++)
the start of loop, how {
many times you want <statement(s)>
to repeat the loop. }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
57
import java.util.Scanner;
Nested Loops
public class RecAngle1
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int height, width; // rectangle's dimensions
char printCharacter; // this character forms the rectangle
GreatestCommonDivisor Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
62
import java.util.Scanner;
public class GreatestCommonDivisor {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
System.out.println("The greatest common divisor for " + n1 +
" and " + n2 + " is " + gcd);
}
} Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
63
Problem: Predicating the Future Tuition- Listing 4.9
FutureTuition Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
64
Problem: Predicating the Future Tuition
Problem: Suppose that the tuition for a university is $10,000 this year
and tuition increases 7% every year. In how many years will the
tuition be doubled?
Before you write this program try to solve this problem first by hand.
public class FutureTuition {
public static void main(String[] args) {
double tuition = 10000; // Year 1
int year = 1;
while (tuition < 20000) {
tuition = tuition * 1.07;
year++;
}
can be approximated as 4 *
x numberOfHits / 1000000.
-1 1
-1 MonteCarloSimulation Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
66
Problem: Monte Carlo Simulation
Web Link: About Monte Carlo Simulation - Introduction
public class MonteCarloSimulation {
public static void main(String[] args) {
final int NUMBER_OF_TRIALS = 10000000;
int numberOfHits = 0;
TestBreak Run
TestContinue.java
TestContinue Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
68
Guessing Number Problem Revisited
Here is a program for guessing a number. You can
rewrite it using a break statement. Listing 4.11
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
PrimeNumber Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
71
Exercise 4_22
Financial application: Loan repayment schedule
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
72
(GUI) Controlling a Loop with a
Confirmation Dialog
A sentinel-controlled loop can be implemented using a confirmation
dialog. The answers Yes or No to continue or terminate the loop. The
template of the loop may look as follows:
int option = 0;
while (option == JOptionPane.YES_OPTION) {
System.out.println("continue loop");
option = JOptionPane.showConfirmDialog(null, "Continue?");
}
SentinelValueUsingConfirmationDialog Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
73