1
Chapter 4 Loops
CS170 Introduction to Computer Science
2
Motivations
Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. System.out.println("Welcome to Java!"); How do you solve this problem?
Objectives
To use while, do-while, and for loop statements to
control the repetition of statements (§§4.2-4.4).
To know the similarities and differences between
three types of loops (§4.5).
To write nested loops (§4.6). To learn the techniques for minimizing numerical
errors (§4.7).
To implement program control with break and
continue (§4.9).
(GUI) To control a loop with a confirmation dialog
(§4.10).
3 4
while Loop Flow Chart
while (loop-continuation-condition) { // loop-body; Statement(s); }
int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }
Loop Continuation Condition? true Statement(s) (loop body) false (count < 100)? true System.out.println("Welcome to Java!"); count++; false (A) (B) count = 0;
5
Trace while Loop
int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }
Initialize count animation
6
Trace while Loop, cont.
int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }
(count < 2) is true animation