- UC. Colorado Springs
CS1150
CS1150 Principles of Computer Science
Loops
Yanyan Zhuang
Department of Computer Science http://www.cs.uccs.edu/~yzhuang
CS1150 Principles of Computer Science Loops Yanyan Zhuang - - PowerPoint PPT Presentation
CS1150 Principles of Computer Science Loops Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Boolean variables o Assume x=3, y=1, true or false? !(x<2) || y>3 If
CS1150
Department of Computer Science http://www.cs.uccs.edu/~yzhuang
CS4500/5500
CS1150
4
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!");
100 times
5
6
loop condition
Note: if the loop continuation condition evaluates to false the first time, the entire while loop is skipped while (loop-continuation-condition) { // loop-body; Statement(s); }
int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }
7
while (loop-continuation-condition) { // loop-body; Statement(s); }
int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }
CS4500/5500
false
9
Initialize count (which we often call control variable)
10
(count < 2) is true
11
Print Welcome to Java
12
Increase count by 1 count is 1 now
13
(count < 2) is still true since count is 1
14
Print Welcome to Java
15
Increase count by 1 count is 2 now
16
(count < 2) is false since count is 2 now
17
The loop exits. Execute the next statement after the loop.
CS4500/5500
count = 1; // Initializes the loop control variable while (count <= 5) { System.out.println("The value of count is " + count); }
CS4500/5500
CS4500/5500
CS4500/5500
expected
System.out.println("I'm going to count to three, ready set...."); count = 1; while (count < 3) { System.out.println(count); count++; }
Output:
I'm going to count to three, ready set.... 1 2
22
23
24
do { // Loop body; Statement(s); } while (loop-continuation-condition);
executed again
to the statement following the loop
Example: TestDoWhile.java
CS4500/5500
condition to true
condition to false
CS4500/5500
CS4500/5500
CS4500/5500
} while (true) {
Statements; }
become false
} while (loop-continuation-condition) {
Statements; Additional statements for controlling the loop; }
CS1150