0% found this document useful (0 votes)
20 views51 pages

Lecture 07

b

Uploaded by

mohanned3909
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)
20 views51 pages

Lecture 07

b

Uploaded by

mohanned3909
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/ 51

Lecture 7

Loops

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
1
Introduction
❑ Suppose that you need to display 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!");
System.out.println("Welcome to Java!");
100 times ...
System.out.println("Welcome to Java!");

So, how do you solve this problem?

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
2
Introduction
❑ Java provides a powerful construct called a loop that
controls how many times an operation or a sequence of
operations is performed in succession.
❑ Using a loop statement, you simply tell the computer to
display a string a hundred times without having to code the
print statement a hundred times, as follows:

int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
3
Introduction
Loops are constructs that control repeated executions of a
block of statements.

The concept of looping is fundamental to programming.

Java provides three types of loop statements:


while loops, do-while loops, and for loops.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
4
while Loop
A while loop statement in Java programming
language repeatedly executes a target statement as
long as a given condition is true.

When executing, if the boolean_expression result is


true, then the actions inside the loop will be
executed. This will continue as long as the
expression result is true.

When the condition becomes false, program control


passes to the line immediately following the loop.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
5
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++;
} }

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
6
while Loop
❑ However, unlike the if statement, after
the body is executed, the condition is
evaluated again. If it is still true, the
body is executed again.

❑ 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.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
7
animation

Trace while Loop


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
8
animation

Trace while Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
9
animation

Trace while Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
10
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
11
animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
12
animation

Trace while Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
13
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
14
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
15
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
16
Problem 1 : Find Sum of Natural
Numbers using while loop

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
17
Problem 2 : Reverse a number using
while Loop

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
18
do-while Loop
While statement first examines its
condition, then executes its body if that
condition is true.

The do statement is similar to the while


statement except that its termination
condition is at the end of the loop body.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
19
do-while Loop
Like the while loop, the do loop
executes the statement in the loop
body until the condition becomes
false.

The condition is written at the end of


the loop to indicate that it is not
evaluated until the loop body is
executed.

Note that the body of a do loop is


always executed at least once.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
20
do-while Loop

Notice that the Boolean expression appears


at the end of the loop, so the statements in
the loop execute once before the Boolean is
tested.

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
21
do-while Loop
If the Boolean expression is true, the
control jumps back up to do
statement, and the statements in the
loop execute again.

This process repeats until the


Boolean expression is false.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
22
do-while Loop
The following code prints the
numbers from 1 to 5 using a do
loop.

int count = 0;
do
{
count++;
System.out.println(count);
}
while (count < 5);

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
23
The Do-while Loop
Example
Example Output

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
24
for Loops
A for loop is a repetition control structure that
allows you to efficiently write a loop that needs to
be executed 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, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
25
for Loops
Before the loop begins, the header of a for loop contains
three parts separated by semicolons.

1. The first part of the header is called the initialization.


2. The second part of the header is the boolean condition.
3. The third part of the header, which is called the increment.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
26
for Loops
for (initial-action; loop-continuation-condition; action-after-each-iteration) {
// loop body;
Statement(s); int i;
} for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
A for loop performs an initial
action once, then repeatedly
executes the statements in the
loop body, and performs an
action after an iteration when
the loop-continuation-
condition evaluates to true.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
27
animation

Trace for Loop


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

The initialization step is executed first, and only once. This step
allows you to declare and initialize any loop control variables and
this step ends with a semi colon (;).

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
28
animation

Trace for Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
animation

Trace for Loop, cont.


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

Next, the Boolean expression is evaluated. If it is true, the body of


the loop is executed. If it is false, the body of the loop will not be
executed and control jumps to the next statement past the for loop.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
30
animation

Trace for Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
31
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

After the body of the for loop gets executed, the control jumps
back up to the update statement. This statement allows you to
update any loop control variables. This statement can be left blank
with a semicolon at the end.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
32
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

The Boolean expression is now evaluated again. If it is true, the


loop executes and the process repeats (body of loop, then update
step, then Boolean expression). After the Boolean expression is
false, the for loop terminates.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
33
animation

Trace for Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
34
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
35
animation

Trace for Loop, cont.


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
36
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
37
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error

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


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

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
38
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error Wrong
{
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, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
39
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, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
40
Nested Loops
Problem1: Write a program that uses nested for
loops to print a multiplication table.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
41
Problem2 : Finding the Greatest Common
Divisor

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
42
Using break and continue
The break statement in Java
programming language has the false
Continuation
following two usages:- condition?

true
When the break statement is
Statement(s)
encountered inside a loop, the
loop is immediately terminated break
and the program control
resumes at the next statement Statement(s)

following the loop.


Next
Statement
It can be used to terminate a
case in the switch statement.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
43
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
sum += number;
if (sum >= 100)
break;
}

System.out.println("The number is " + number);


System.out.println("The sum is " + sum);
}
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
44
Using break and continue
Examples for using the break and continue
keywords:

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
45
Using break and continue
The continue keyword can be used in any of the loop control
structures.
It causes the loop to immediately jump to the next iteration
of the loop.
1. In a for loop, the continue keyword causes control to immediately
jump to the update statement.
2. In a while loop or do/while loop, control immediately jumps to the
Boolean expression.

The continue statement is similar to a break, but the loop


condition is evaluated again, and the loop body is executed
again if it is still true.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
46
Using break and continue
false
Continue
condition?

true

Statement(s)

continue

Statement(s)

Next
Statement
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
47
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
if (number == 10 || number == 11)
continue;
sum += number;
}

System.out.println("The sum is " + sum);


}
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
48
Using break and continue
Examples for using the break and continue
keywords:

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
49
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward.
The words “mom,” “dad,” and “noon,” for instance, are all
palindromes.
The problem is to write a program that prompts the user to enter a
string and reports whether the string is a palindrome. One solution is
to check whether the first character in the string is the same as the last
character. If so, check whether the second character is the same as the
second-to-last character. This process continues until a mismatch is
found or all the characters in the string are checked, except for the
middle character if the string has an odd number of characters.
low high

String s a b c d e f g n h g f e d c b a

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
50
Problem: Checking Palindrome

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
51

You might also like