14 April 2003 This lecture covers the reading in Chapter 5: Control Statements |
Selection Statements
|
if( boolean expression ) { statement1; ... statementn; }
Note: Curly braces only required if there is more than one execution statement.
if( x == y ) {
// do this
} else {
// do this
}
Note: The "else" is for the last statement.
if( x == y ) { // do this } else if( x > y ) { // nested 'if' // do this // Note: any number of "else if" clauses after "if" and before "else" } else { // do this }
Note: The "else" is for the last statement.
The output is:
x not > or = to y
The output is:
On Monday my wallet contained $25 I'll spend $5 on Monday for lunch I have $20 to spend on lunch for the rest of the week On Tuesday my wallet contained $20 I'll spend $6 on Tuesday for lunch I have $14 to spend on lunch for the rest of the week On Wednesday my wallet contained $14 I'll spend $6 on Wednesday for lunch I have $8 to spend on lunch for the rest of the week On Thursday my wallet contained $8 I'll spend $8 on Thursday for lunch I have $0 to spend on lunch for the rest of the week On Friday my wallet contained $0 I'll spend $3 on Friday for lunch I have $-3 to spend on lunch for the rest of the week If I want to eat the rest of the week I better visit my friendly neighborhood ATM!
A while loop:
The output of the while loop is equivalent to that of the corresponding for loop:
96 is a multiple of 8 88 is a multiple of 8 80 is a multiple of 8 72 is a multiple of 8 64 is a multiple of 8 56 is a multiple of 8 48 is a multiple of 8 40 is a multiple of 8 32 is a multiple of 8 24 is a multiple of 8 16 is a multiple of 8 8 is a multiple of 8 The while loop above is a pre-test loop because it evaluates the boolean expression in line 14 before executing lines 15-17.
The do while loop is a post-test.
The test in a post-test loop is at the end of the loop.
We saw this last week in do .. while.
We saw this in scope in a for loop example
outer loop value i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 outer loop value i = 1 j = 1 j = 2 j = 3 j = 4 outer loop value i = 2 j = 2 j = 3 j = 4 outer loop value i = 3 j = 3 j = 4 outer loop value i = 4 j = 4
The break statement causes
execution to exit the current loop.
In this example, the break occurs in an inner loop, but the outer loop remains
unaffected.
The output is:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete.
This example uses the continue
statement to force iteration to continue as long as the boolean test results in
true.
What operators does the boolean test use? I
The output is:
0 1 2 3 4 5 6 7 8 9
Here's a more complex use of the continue statement:
The output is:
0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81
Let's go on to objects and get our homework from that lecture.
______________
course
homepage course
calendar