Download presentation
Presentation is loading. Please wait.
1
COMP 110 Switch Statements and Loops Tabitha Peck M.S. February 6, 2008 MWF 3-3:50 pm Philips 367 1
2
Announcements Friday - No Lab! Bring questions on Project 2 Grades online next week 2
3
Questions? 3
4
Switch Statements switch (numOfSiblings) { case 0: System.out.print(“An only child”); break; case 1: System.out.print(“Just one you say”); break; case 2: System.out.print(“Two siblings!”); break; case 3: System.out.print(“Big family!”); break; default: System.out.print(“I don’t believe you”); break; } 4 Controlling expression int or char ONLY! Break statement Case label
5
Practice with Switch statements Write a switch statement that takes as controlling expression your year in college (as int) and outputs your year in college as freshman, sophomore, junior, senior, or super senior
6
Shorthand for if / else 6 if (n1 > n2 ) max = n1; else max = n2; max = (n1 > n2) ? n1 : n2;
7
Loops Loop - part of program that repeats Body - statements being repeated Iteration - each repetition of body Stopping condition 7
8
Types of Loops while Safest choice Not always most elegant do-while Loop iterates at least ONCE for Numeric computation changes by equal amount 8
9
While Loops count = 1; while (count <= num) { System.out.print(count + “, “); count++; } 1, 2, 3, 4, 5, 6, … num 9
10
While Loops Evaluate Boolean Expression Execute Body End loop true false 10
11
Do-while Loops count = 1; do { System.out.print(count + “, “); count++; } while (count <= num); 1, 2, 3, 4, 5, 6, … num 11
12
Do-while Loops Evaluate Boolean Expression Execute Body End loop true false 12 Execute Body
13
For Loops int count; // initializing action; boolean expression; update action for (count = 1; count <= num; count++) { System.out.print(count + “, “); } 1, 2, 3, 4, 5, 6, … num 13
14
For Loops Evaluate Boolean Expression Execute Body End loop true false 14 Execute Initializing Action Execute Update Action
15
Types of Loops while Safest choice Not always most elegant do-while Loop iterates at least ONCE for Numeric computation changes by equal amount 15
16
Bugs Problem with program preventing correct execution Infinite Loops!!!!!! 16
17
Infinite Loops count = 1; while (count <= num) { System.out.print(count + “, “); //count++; } 17
18
Infinite Loops count = 1; while (count <= num); { System.out.print(count + “, “); count++; } 18
19
Infinite Loops int count; // initializing action; boolean expression; update action for (count = 1; count >= num; count++) { System.out.print(count + “, “); } 19
20
Friday Help with Program 2 20
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.