SlideShare a Scribd company logo
1 
SSttrruuccttuurree pprrooggrraammmmiinngg 
JJaavvaa PPrrooggrraammmmiinngg –– TThheeoorryy 
CChhaapptteerr 44 LLooooppss 
FFaaccuullttyy ooff PPhhyyssiiccaall aanndd BBaassiicc 
EEdduuccaattiioonn 
CCoommppuutteerr SScciieennccee 
BByy:: MMsscc.. KK aarrwwaann MM.. 
KKaarreeeemm 
22001144 -- 22001155
2 
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!"); 
So, how do you solve this problem?
3 
Opening 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!"); 
… 
… 
… 
System.out.println("Welcome to Java!"); 
System.out.println("Welcome to Java!"); 
System.out.println("Welcome to Java!"); 
Problem: 
100 
times
4 
Introducing while Loops 
int count = 0; 
while (count < 100) { 
System.out.println("Welcome to Java"); 
count++; 
}
5 
Objectives 
 To write programs for executing statements repeatedly using a while loop. 
 To develop a program for Guess Number and Subtraction Quiz Loop. 
 To follow the loop design strategy to develop loops. 
 To develop a program for Subtraction Quiz Loop. 
 To control a loop with a sentinel value. 
 To obtain large input from a file using input redirection rather than typing from 
the keyboard . 
 To write loops using do-while statements. 
 To write loops using for statements. 
 To discover the similarities and differences of three types of loop statements. 
 To write nested loops. 
 To learn the techniques for minimizing numerical errors. 
 To learn loops from a variety of examples (GCD, FutureTuition, 
MonteCarloSimulation). 
 To implement program control with break and continue. 
 (GUI) To control a loop with a confirmation dialog .
6 
while Loop Flow Chart 
Initial action ( start the loop) 
while (loop-continuation-condition) { 
// loop-body; ( End of the loop) 
Statement(s); 
iteration (increment or decrement) 
} 
int count = 0; 
while (count  100) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Loop 
Continuation 
Condition? 
true 
Statement(s) 
(loop body) 
false 
count = 0; 
(count  100)? 
true 
false 
System.out.println(Welcome to Java!); 
count++; 
(A) (B)
7 
Trace while Loop 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Initialize count
8 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
(count  2) is true
9 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Print Welcome to Java
10 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Increase count by 1 
count is 1 now
11 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
(count  2) is still true since 
count is 1
12 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Print Welcome to Java
13 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
Increase count by 1 
count is 2 now
14 
Trace while Loop, cont. 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
(count  2) is false since count is 
2 now
15 
Trace while Loop 
int count = 0; 
while (count  2) { 
System.out.println(Welcome to Java!); 
count++; 
} 
The loop exits. Execute the next 
statement after the loop.
16 
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: 
double item = 1; double sum = 0; 
while (item != 0) { // No guarantee item will be 0 
sum += item; 
item -= 0.1; 
} 
System.out.println(sum); 
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.
17 
do-while Loop 
do { 
// Loop body; 
Statement(s); 
Statement(s) 
(loop body) 
Loop 
Continuation 
Condition? 
true 
false 
} while (loop-continuation-condition);
18 
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!); 
} 
Initial-Action 
Loop 
Continuation 
Condition? 
true 
Statement(s) 
(loop body) 
false 
Action-After-Each-Iteration 
(A) 
i = 0 
(i  100)? 
true 
System.out.println( 
Welcome to Java); 
false 
i++ 
(B)
19 
Trace for Loop 
int i; 
for (i = 0; i  2; i++) { 
System.out.println( 
Welcome to Java!); 
} 
Declare i
20 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println( 
Welcome to Java!); 
} 
Execute initializer 
i is now 0
21 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println( Welcome to Java!); 
} 
(i  2) is true 
since i is 0
22 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
Print Welcome to Java
23 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
Execute adjustment statement 
i now is 1
24 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
(i  2) is still true 
since i is 1
25 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
Print Welcome to Java
26 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
Execute adjustment statement 
i now is 2
27 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
(i  2) is false 
since i is 2
28 
Trace for Loop, cont. 
int i; 
for (i = 0; i  2; i++) { 
System.out.println(Welcome to Java!); 
} 
Exit the loop. Execute the next 
statement after the loop
29 
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 
}
30 
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 iinnffiinniittee lloooopp, is correct. Nevertheless, it is 
better to use the equivalent loop in (b) to avoid confusion: 
for ( ; ; ) { 
// Do something 
} 
(a) 
Equivalent while (true) { 
// Do something 
} 
(b)
31 
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; i10; i++); 
{ 
System.out.println(i is  + i); 
}
32 
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 (i10); 
Correct
for ( ; loop-continuation-condition; ) // Loop body 
} 
initial-action; 
while (loop-continuation-condition) { 
33 
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): 
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 
for (initial-action; 
loop-continuation-condition; 
action-after-each-iteration) { 
// Loop body; 
} 
(a) 
Equivalent 
// Loop body; 
action-after-each-iteration; 
(b) 
} 
while (loop-continuation-condition) { 
// Loop body 
} 
(a) 
Equivalent 
(b)
34 
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.
35 
Nested Loops 
Problem: Write a program that uses nested for 
loops to print a multiplication table. 
Note: look practical part
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? 
36 
Note: look practical part
Problem: Predicating the Future Tuition 
double tuition = 10000; int year = 1 // Year 1 
tuition = tuition * 1.07; year++; // Year 2 
tuition = tuition * 1.07; year++; // Year 3 
tuition = tuition * 1.07; year++; // Year 4 
... 
37
38 
Using break and continue 
Examples for using the break and continue 
keywords:
Problem: Displaying Prime Numbers 
Problem: 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. 
Solution: The problem can be broken into the following tasks: 
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. 
•Determine whether a given number is prime. 
•Count the prime numbers. 
•Print each prime number, and print 10 numbers per line. 
39
(GUI) Controlling a Loop with a 
40 
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?); 
}

More Related Content

What's hot (20)

PDF
Java conditional statements
Kuppusamy P
 
PPTX
Application of Stack - Yadraj Meena
Dipayan Sarkar
 
PPT
OOP V3.1
Sunil OS
 
PDF
Python cheat-sheet
srinivasanr281952
 
PPT
Java Basics V3
Sunil OS
 
PDF
An Introduction to Programming in Java: Arrays
Martin Chapman
 
PPT
Collection v3
Sunil OS
 
PPTX
Operators in Python
Anusuya123
 
PDF
Introduction To Autumata Theory
Abdul Rehman
 
PPTX
Data structure by Digvijay
Digvijay Singh Karakoti
 
PPTX
This pointer
Kamal Acharya
 
PPTX
Python
Gagandeep Nanda
 
DOCX
Java practical
shweta-sharma99
 
PDF
Python Programming
Sreedhar Chowdam
 
PPTX
C++ IF STATMENT AND ITS TYPE
UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA
 
PDF
Java Arrays
OXUS 20
 
PDF
Java 8 lambda expressions
Logan Chien
 
PPTX
Nested loops
Neeru Mittal
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
PDF
Operators in python
Prabhakaran V M
 
Java conditional statements
Kuppusamy P
 
Application of Stack - Yadraj Meena
Dipayan Sarkar
 
OOP V3.1
Sunil OS
 
Python cheat-sheet
srinivasanr281952
 
Java Basics V3
Sunil OS
 
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Collection v3
Sunil OS
 
Operators in Python
Anusuya123
 
Introduction To Autumata Theory
Abdul Rehman
 
Data structure by Digvijay
Digvijay Singh Karakoti
 
This pointer
Kamal Acharya
 
Java practical
shweta-sharma99
 
Python Programming
Sreedhar Chowdam
 
Java Arrays
OXUS 20
 
Java 8 lambda expressions
Logan Chien
 
Nested loops
Neeru Mittal
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Operators in python
Prabhakaran V M
 

Viewers also liked (12)

PPT
Looping statements in Java
Jin Castor
 
PPTX
The Loops
Krishma Parekh
 
PDF
Event loops in java script 01 - stack
Vishnu Padmanabhan
 
PDF
Loops in JavaScript
Florence Davis
 
PPTX
Do...while loop structure
Jd Mercado
 
PPTX
Loops in java script
Ravi Bhadauria
 
PDF
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
PPTX
Do While and While Loop
Hock Leng PUAH
 
PPTX
While , For , Do-While Loop
Abhishek Choksi
 
PPTX
C++ loop
Khelan Ameen
 
PPTX
Loops c++
Shivani Singh
 
PPTX
Loops Basics
Mushiii
 
Looping statements in Java
Jin Castor
 
The Loops
Krishma Parekh
 
Event loops in java script 01 - stack
Vishnu Padmanabhan
 
Loops in JavaScript
Florence Davis
 
Do...while loop structure
Jd Mercado
 
Loops in java script
Ravi Bhadauria
 
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
Do While and While Loop
Hock Leng PUAH
 
While , For , Do-While Loop
Abhishek Choksi
 
C++ loop
Khelan Ameen
 
Loops c++
Shivani Singh
 
Loops Basics
Mushiii
 
Ad

Similar to Java Programming: Loops (20)

PPT
Week2 ch4 part1edited 2020
Osama Ghandour Geris
 
PPT
Week2 ch4 part1edited 2020
Osama Ghandour Geris
 
PPT
04slidemicroemulsions microemulsions microemulsions microemulsions microemuls...
AhmadHashlamon
 
PPT
04 slide loops
hazem15
 
PPT
object orineted programming looping .ppt
zeenatparveen24
 
PPT
Lecture on repetition statements (loops)
MustajabHussain9
 
PDF
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
PPT
Ch5(loops)
Uğurcan Uzer
 
PPT
Java™ (OOP) - Chapter 4: "Loops"
Gouda Mando
 
PPT
Ch4_part1.ppt
RuthikReddyGarlapati
 
PPT
Ch4_part1.ppt
ssuserc70988
 
PPT
C Programming Looping Statements For Students
SoumyaKantiSarkar2
 
PPT
CH5.ppt chatpter2 introduction dddto OOP
belalAbdullah5
 
PPTX
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
zainaimadsaed
 
PDF
ICP - Lecture 9
hassaanciit
 
PPT
Repetition Structure
PRN USM
 
PPT
Java căn bản - Chapter6
Vince Vo
 
PPTX
Cs1123 6 loops
TAlha MAlik
 
PPTX
130707833146508191
Tanzeel Ahmad
 
PPTX
06.Loops
Intro C# Book
 
Week2 ch4 part1edited 2020
Osama Ghandour Geris
 
Week2 ch4 part1edited 2020
Osama Ghandour Geris
 
04slidemicroemulsions microemulsions microemulsions microemulsions microemuls...
AhmadHashlamon
 
04 slide loops
hazem15
 
object orineted programming looping .ppt
zeenatparveen24
 
Lecture on repetition statements (loops)
MustajabHussain9
 
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
Ch5(loops)
Uğurcan Uzer
 
Java™ (OOP) - Chapter 4: "Loops"
Gouda Mando
 
Ch4_part1.ppt
RuthikReddyGarlapati
 
Ch4_part1.ppt
ssuserc70988
 
C Programming Looping Statements For Students
SoumyaKantiSarkar2
 
CH5.ppt chatpter2 introduction dddto OOP
belalAbdullah5
 
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
zainaimadsaed
 
ICP - Lecture 9
hassaanciit
 
Repetition Structure
PRN USM
 
Java căn bản - Chapter6
Vince Vo
 
Cs1123 6 loops
TAlha MAlik
 
130707833146508191
Tanzeel Ahmad
 
06.Loops
Intro C# Book
 
Ad

More from Karwan Mustafa Kareem (8)

PPTX
Computer and network security
Karwan Mustafa Kareem
 
PPT
Java programming: Elementary practice
Karwan Mustafa Kareem
 
PPT
Java Programmin: Selections
Karwan Mustafa Kareem
 
PPT
Java programming: Elementary programming
Karwan Mustafa Kareem
 
PPT
Introduction to Java Programming Language
Karwan Mustafa Kareem
 
PPTX
Cryptography
Karwan Mustafa Kareem
 
PPTX
MySQL Database with phpMyAdmin
Karwan Mustafa Kareem
 
PPT
Database Application with MySQL
Karwan Mustafa Kareem
 
Computer and network security
Karwan Mustafa Kareem
 
Java programming: Elementary practice
Karwan Mustafa Kareem
 
Java Programmin: Selections
Karwan Mustafa Kareem
 
Java programming: Elementary programming
Karwan Mustafa Kareem
 
Introduction to Java Programming Language
Karwan Mustafa Kareem
 
Cryptography
Karwan Mustafa Kareem
 
MySQL Database with phpMyAdmin
Karwan Mustafa Kareem
 
Database Application with MySQL
Karwan Mustafa Kareem
 

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
July Patch Tuesday
Ivanti
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Python basic programing language for automation
DanialHabibi2
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 

Java Programming: Loops

  • 1. 1 SSttrruuccttuurree pprrooggrraammmmiinngg JJaavvaa PPrrooggrraammmmiinngg –– TThheeoorryy CChhaapptteerr 44 LLooooppss FFaaccuullttyy ooff PPhhyyssiiccaall aanndd BBaassiicc EEdduuccaattiioonn CCoommppuutteerr SScciieennccee BByy:: MMsscc.. KK aarrwwaann MM.. KKaarreeeemm 22001144 -- 22001155
  • 2. 2 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!"); So, how do you solve this problem?
  • 3. 3 Opening 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!"); … … … System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); Problem: 100 times
  • 4. 4 Introducing while Loops int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }
  • 5. 5 Objectives To write programs for executing statements repeatedly using a while loop. To develop a program for Guess Number and Subtraction Quiz Loop. To follow the loop design strategy to develop loops. To develop a program for Subtraction Quiz Loop. To control a loop with a sentinel value. To obtain large input from a file using input redirection rather than typing from the keyboard . To write loops using do-while statements. To write loops using for statements. To discover the similarities and differences of three types of loop statements. To write nested loops. To learn the techniques for minimizing numerical errors. To learn loops from a variety of examples (GCD, FutureTuition, MonteCarloSimulation). To implement program control with break and continue. (GUI) To control a loop with a confirmation dialog .
  • 6. 6 while Loop Flow Chart Initial action ( start the loop) while (loop-continuation-condition) { // loop-body; ( End of the loop) Statement(s); iteration (increment or decrement) } int count = 0; while (count 100) { System.out.println(Welcome to Java!); count++; } Loop Continuation Condition? true Statement(s) (loop body) false count = 0; (count 100)? true false System.out.println(Welcome to Java!); count++; (A) (B)
  • 7. 7 Trace while Loop int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } Initialize count
  • 8. 8 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } (count 2) is true
  • 9. 9 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } Print Welcome to Java
  • 10. 10 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } Increase count by 1 count is 1 now
  • 11. 11 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } (count 2) is still true since count is 1
  • 12. 12 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } Print Welcome to Java
  • 13. 13 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } Increase count by 1 count is 2 now
  • 14. 14 Trace while Loop, cont. int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } (count 2) is false since count is 2 now
  • 15. 15 Trace while Loop int count = 0; while (count 2) { System.out.println(Welcome to Java!); count++; } The loop exits. Execute the next statement after the loop.
  • 16. 16 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: double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum); 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.
  • 17. 17 do-while Loop do { // Loop body; Statement(s); Statement(s) (loop body) Loop Continuation Condition? true false } while (loop-continuation-condition);
  • 18. 18 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!); } Initial-Action Loop Continuation Condition? true Statement(s) (loop body) false Action-After-Each-Iteration (A) i = 0 (i 100)? true System.out.println( Welcome to Java); false i++ (B)
  • 19. 19 Trace for Loop int i; for (i = 0; i 2; i++) { System.out.println( Welcome to Java!); } Declare i
  • 20. 20 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println( Welcome to Java!); } Execute initializer i is now 0
  • 21. 21 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println( Welcome to Java!); } (i 2) is true since i is 0
  • 22. 22 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } Print Welcome to Java
  • 23. 23 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } Execute adjustment statement i now is 1
  • 24. 24 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } (i 2) is still true since i is 1
  • 25. 25 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } Print Welcome to Java
  • 26. 26 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } Execute adjustment statement i now is 2
  • 27. 27 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } (i 2) is false since i is 2
  • 28. 28 Trace for Loop, cont. int i; for (i = 0; i 2; i++) { System.out.println(Welcome to Java!); } Exit the loop. Execute the next statement after the loop
  • 29. 29 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 }
  • 30. 30 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 iinnffiinniittee lloooopp, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion: for ( ; ; ) { // Do something } (a) Equivalent while (true) { // Do something } (b)
  • 31. 31 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; i10; i++); { System.out.println(i is + i); }
  • 32. 32 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 (i10); Correct
  • 33. for ( ; loop-continuation-condition; ) // Loop body } initial-action; while (loop-continuation-condition) { 33 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): 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 for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; } (a) Equivalent // Loop body; action-after-each-iteration; (b) } while (loop-continuation-condition) { // Loop body } (a) Equivalent (b)
  • 34. 34 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.
  • 35. 35 Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. Note: look practical part
  • 36. 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? 36 Note: look practical part
  • 37. Problem: Predicating the Future Tuition double tuition = 10000; int year = 1 // Year 1 tuition = tuition * 1.07; year++; // Year 2 tuition = tuition * 1.07; year++; // Year 3 tuition = tuition * 1.07; year++; // Year 4 ... 37
  • 38. 38 Using break and continue Examples for using the break and continue keywords:
  • 39. Problem: Displaying Prime Numbers Problem: 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. Solution: The problem can be broken into the following tasks: •For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. •Determine whether a given number is prime. •Count the prime numbers. •Print each prime number, and print 10 numbers per line. 39
  • 40. (GUI) Controlling a Loop with a 40 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?); }