0% found this document useful (0 votes)
13 views63 pages

Lecture-10: by Dr. Bharati Mishra

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views63 pages

Lecture-10: by Dr. Bharati Mishra

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Lecture-10

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

2. To iterate through data and test for certain


condition
E.g. Checking input data, until user wants to “quit”

3. To keep attempting for some operation


E.g obtaining data from a remote computer over a
network) until we succeed
while Loop
while Loop
while(condition)
{
statement;
}
1. If the condition is true, the statement is
executed; then the condition is evaluated again

2. The statement is executed over and over until
the condition becomes false.
3. When the loop finishes, control passes to the
next instruction in the program, following the
closing curly brace of the loop.
while

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

(count < 2) is true

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program

Print “Welcome to Java!”

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

(count < 2) is still true.

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program

Print “Welcome to Java!”

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

(count < 2) is now false.

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

double item = 1.0;


while (item != 0.0) {
// No guarantee item will be 0
item -= 0.1;
}

• There is no guarantee that item will be exactly


0: actually an infinite loop!
Tip
• Avoid using literals directly in code as much as
possible (good programming style)

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.

• Write a program that reads and calculates the


sum of an unspecified number of integers. The
input 0 signifies the end of the input.

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=0; X int i=0;


while (i < 10); do {
{ System.out.println(i);
System.out.println(i); i++;
i++; } while (i<10);
}

• BUT in case of do-while ; is required.


for Loop
for loop
int count = 0;
while (count < 10)
{
System.out.println("Welcome to Java!");
count++;
}

for(int count =0; count < 10; count ++)


{
System.out.println("Welcome to Java!");
}
for loop
for (initial-action;
continuation-condition;
action-after-each-iteration)
{
// loop body….
}

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:

for( int Count = 0; Count < 10; Count++ )


{
....;
}
for loop
More Tips
• The initial-action statement is carried out once
only, at the start of the first time that the loop is
entered.
• The continuation-condition is tested before each
execution of the body of the loop, including a test
before the very first execution of the loop.
• The third expression (i.e
action-after-each-iteration) is a statement
executed after every execution of the loop body,
before the next test. It typically increments a
counter.
for Loop

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!");
}

Print Welcome to Java


for Loop
Execute adjustment
statement
i now is 1

int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop

(i < 2) is still true


since i is 1

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!");
}

Print Welcome to Java


for Loop
Execute adjustment
statement
i now is 2

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!");
}

Exit the loop. Execute the next


statement after the loop
CAUTION!
• The initial-action in a for loop is a list of zero or
more comma-separated expressions
• The action-after-each-iteration in a for loop is 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++));

for (int i = 0, j = 0; (i + j < 10); i++, j++) {


// Do something

}
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!

for (int i=0; i<10; i++);


{
System.out.println("i is " + i);
}

• (here ; is executed as for loop statement,


therefore we won’t see any output)
Program
• Write a program that sums a series that starts
with 0.01 and ends with 1.0. The numbers in the
series will increment by 0.01, as follows: 0.01 +
0.02 + 0.03 and so on.

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

• continue causes the rest of the current round of


the loop to be skipped.
• Break causes the loop to be skipped overall.
• Those two keywords might be useful sometimes
• But they make programs more difficult to read
• So use them rarely
• Use a boolean flag instead
Program
• Examples for using the break and continue
keywords:

● 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

You might also like