Lecture-10: by Dr. Bharati Mishra
Lecture-10: by Dr. Bharati Mishra
By
Dr. Bharati Mishra
Loops
Motivation
• Suppose we want to show “Java is fun!” 100 times.
How do we do that?
• Repeat the following statement 100 times!?
System.out.println("Welcome to Java!");
Naïve Solution
• Naïve solution
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!");
Better Solution
• Better solution
• Using loop
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
Why Loops?
1. To automate the repetition of calculations
E.g. compute the profit for “a number of different months”
of a company's sale
int count = 0;
while (loop-condition) {
while (count < 100) {
// loop-body; System.out.println("Welcome to Java!");
Statement(s); count++;
} }
Trace Program
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
count is now 1.
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
count is now 2.
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Loop exit
Caution!
• No ; at the end of while
No ; here!
int count = 0;
while (count < 100)
{
System.out.println("Welcome to Java!");
count++;
}
Caution!
• The body of a while loop must eventually make
the condition false
• If not, it is an infinite loop, which will execute until
the user interrupts the program!
int count = 1;
while (count > 0)
{
System.out.println("Welcome to Java!");
count++;
}
CAUTION!
• Don’t use floating-point values for equality
checking in a loop control!
• Floating-point values are approximations
int count = 0;
final int REPEATS = 100;
while (count < REPEATS )
{
System.out.println(“Java");
count++;
}
System.out.println(REPEATS + “ Times” );
Tip
• To repeat a loop 10 times, you generally write a
loop “not from 1 to 10”, but “from 0 to 9”.
• All counting in Java tends to start at zero rather
than one. This is a convention that most Java
programmers adopt.
• Again: good programming style
Program
• 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.
GuessNumberOneTime
GuessNumber
Program
• Write a program that prompts the user to enter
two positive integers and finds their greatest
common divisor.
GreatestCommonDivisor Run
Program
• 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?
FutureTuition Run
Program
• Often the number of times a loop is executed is
not predetermined. You may use an input value
to signify the end of the loop. Such a value is
known as a sentinel value.
SentinelValue
Program
• 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
Program
• This example gives a program that generates five
questions and reports the number of the correct
answers after a student answers all five
questions.
SubtractionQuizLoop
do-while Loop
do-while
• Will be executed at least once
do {
// Loop body;
Statement(s);
} while (loop-condition);
Caution!
• ; at the end of while
int count = 0;
do
{
System.out.println("Welcome to Java!");
count++;
} while (count < 100) ;
; here!
CAUTION!
• Do NOT add a semicolon at the end of the while
clause:
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
Tip
• It is common to declare the loop variable at the
start of the for loop itself:
Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
Execute initializer
i is now 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
(i < 2) is true
since i is 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
(i < 2) is false
since i is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
}
CAUTION!
• If the loop-continuation-condition in a for loop is
omitted, it is implicitly true.
CAUTION!
• Do NOT add a semicolon at the end of the for
clause:
Don’t do
this!
TestSum
Program
• Write a program that uses nested for loops to
print a multiplication table.
MultiplicationTable
Which Loop?
• All loops are equal
Which Loop?
• Some recommendations
1. Use the most intuitive loop
2. If number of repetitions known for
3. If number of repetitions unknown while
4. If should be executed at least once (before testing
the condition) do-while
Break/continue
break
• break causes the loop to be abandoned, and
execution continues following the closing curly
brace.
while ( i > 0 )
{
....
if ( j == .... )
break; // abandon the loop
….
}
// end of the loop body
break will bring
you here
continue
• continue causes the rest of the current round of
the loop to be skipped.
• "while" or "do" loop moves directly to the next
condition test of the loop.
• "for" loop moves to the
“action-after-each-iteration” expression, and then to
the condition test.
Continue/break
● TestBreak.java
TestBreak
● TestContinue.java
TestContinue
Program
• Here is a program for guessing a number. You
can rewrite it using a break statement.
GuessNumberUsingBreak
Program
• Write a program that displays the first 50 prime
numbers in five lines, each of which contains 10
numbers. An integer greater than 1 is prime if its
only positive divisor is 1 or itself. For example, 2, 3,
5, and 7 are prime numbers, but 4, 6, 8, and 9 are
not.
PrimeNumber Run