0% found this document useful (0 votes)
14 views

Introduction to Java_chapter4

Chapter 4 covers loops in programming, including while, do-while, and for loops, along with their syntax and examples. It emphasizes the importance of using appropriate data types for loop conditions and provides cautionary notes on common mistakes. The chapter also discusses the use of break and continue keywords to control loop execution.

Uploaded by

Mohammed Breka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Introduction to Java_chapter4

Chapter 4 covers loops in programming, including while, do-while, and for loops, along with their syntax and examples. It emphasizes the importance of using appropriate data types for loop conditions and provides cautionary notes on common mistakes. The chapter also discusses the use of break and continue keywords to control loop execution.

Uploaded by

Mohammed Breka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Chapter 4 Loops

Lecture notes for computer programming 1


Faculty of Engineering and Information Technology
Prepared by: Iyad Albayouk

١
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++;
} }
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true tru
e
Statement(s) System.out.println("Welcome to
(loop body) Java!");
count++;

(A) (B)

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

٣
Caution
Don’t use floating-point values for equality
checking in a loop control. Since floating-point
values are approximations, using them could result
in imprecise counter values and inaccurate results.
This example uses int value for data. If a floating-
point type value is used for data, (data != 0) may
be true even though data is 0.

// data should be zero


double data = Math.pow(Math.sqrt(2), 2) - 2;

if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero"); ٤
do-while Loop

Statement(s)
(loop body)

true Loop
Continuation
do { Condition?
// Loop body; false
Statement(s);
} while (loop-continuation-condition);

٥
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) System.out.println(
{ "Welcome to Java!");
// loop body;
Statement(s); }
}
I n it ia l - A c t i o n i = 0

Loop
fa ls e fa ls e
C o n t i n u a t io n (i < 1 0 0 )?
C o n d itio n ?
tru e tr u e
S ta te m en t(s) S y s te m .o u t.p r in t ln (
(lo o p b o d y ) " W e lc o m e t o

A c t io n -A fte r -E a c h -I t e r a t io n i+ +

(A ) ٦
(B )
Example for Loop

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

٧
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++));

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


// Do something
}
٨
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

٩
Example: Using for Loops
Problem: 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.

public class TestSum {


public static void main(String[] args) {
// Initialize sum
float sum = 0;
// Add 0.01, 0.02, ..., 0.99, 1 to sum
for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
sum += i;
// Display result
System.out.println("The sum is " + sum);
}
}
١٠
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.

Next slide has a program to print a multiplication


table. ١١
import javax.swing.JOptionPane;
public class TestMultiplicationTable {
public static void main(String[] args) {
String output = " Multiplication Table\n"; output += "------
------------------\n";
output += " | ";
for (int j = 1; j <= 9; j++)
output += " " + j;
output += "\n";
for (int i = 1; i <= 9; i++) {
output += i + " | ";
for (int j = 1; j <= 9; j++) {
if (i * j < 10)
output += " " + i * j;
else
output += " " + i * j;
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output); }}
١٢
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)
١٣
Recommendations
Use the one that is most intuitive and comfortable for
you. 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. 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. 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.

١٤
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++);


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

١٥
Caution, cont.
Similarly, the following loop is also wrong:
int i=0; Logic Error
while (i < 10);
{
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++; Correct
} while (i<10);
١٦
Using break
Examples for using the break keyword:
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);
}
}
١٧
Using continue
Examples for using the continue keyword:

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

١٨

You might also like