Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)

Similar presentations


Presentation on theme: "1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)"— Presentation transcript:

1 1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)

2 Are there any Weaknesses in the if Statement? For some problems, the "waterfall" execution of the multi-branch if leads to poor (or perhaps unacceptable) performance of a program. Example: Suppose we need a function that, given the number of a day of the week (1-7), computes its corresponding name (Sunday- Saturday)? 2

3 Algorithm: 0. Receive dayNumber. 1. If dayNumber == 1: Return "Sunday". Else if dayNumber == 2: Return "Monday". Else if dayNumber == 3: Return "Tuesday". Else if dayNumber == 4: Return "Wednesday". Else if dayNumber == 5: Return "Thursday". Else if dayNumber == 6: Return "Friday". Else if dayNumber == 7: Return "Saturday". Else Display an error message, and return "". 3

4 // Receive a day number, return its name string dayName(int dayNumber) { if (dayNumber == 1) return "Sunday"; else if (dayNumber == 2) return "Monday"; else if (dayNumber == 3) return "Tuesday"; else if (dayNumber == 4) return "Wednesday"; else if (dayNumber == 5) return "Thursday"; else if (dayNumber == 6) return "Friday"; else if (dayNumber == 7) return "Saturday"; else { cerr << "\n** DayName: invalid day number\n"; return ""; } 4

5 The multi-branch if has ______________________ time: Computing "Sunday" requires ___ comparison Computing "Sunday" requires ___ comparison Computing "Monday" requires ___ comparisons Computing "Monday" requires ___ comparisons...... Computing "Saturday" requires ___ comparisons Computing "Saturday" requires ___ comparisons Computations that are "later" in the if take longer.  Computations that are "later" in the if take longer. There are situations where the time to select one of many statements must be ________________. 5

6 A Solution The C++ _________ statement provides an alternative: string DayName(int dayNumber) { ________________________________ ___ _____________________ _____________________________ case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Wednesday"; case 5: return "Thursday"; case 6: return "Friday"; case 7: return "Saturday"; _____________ cerr << "\n* DayName: invalid day number\n"; return ""; ___ } 6 Cases need not be in order nor consecutive, and there can be multiple labels.

7 The switch Statement The switch statement provides multi-branch selection, but guarantees _________________________, regardless of which branch is selected. Thus, the time to select return "Saturday"; is identical to the time to select return "Sunday"; if a switch statement is used to select them. 7

8 8 Pattern: switch (expression) { caseList 1 StatementList 1 caseList 2 StatementList 2... caseList N StatementList N default: StatementList N+1 } where expression is an integer-compatible expression, each caseList is one or more cases of this form: case ConstantValue : and each StatementList usually ends with a break or return statement.

9 Warning C++ switch statements exhibit ________________ behavior. 1. expression is evaluated. 2. If expression == constant i, control jumps to the Statement associated with constant i. 3. Control continues ______________ until: 3. Control continues ______________ the switch statement until: a. The end of the switch is reached; b. A is executed, terminating the switch; b. A break is executed, terminating the switch; c. A is executed, terminating the function; or c. A return is executed, terminating the function; or d. An is executed, terminating the program. d. An exit() is executed, terminating the program. 9

10 Output: ______________________________ 10 Example What will the following statement display, if the value of is 6? What will the following statement display, if the value of dayNumber is 6? switch(dayNumber) { case 1: cout << "Sunday"; case 2: cout << "Monday"; case 3: cout << "Tuesday"; case 4: cout << "Wednesday"; case 5: cout << "Thursday"; case 6: cout << "Friday"; case 7: cout << "Saturday"; default: cout << "Error!" << endl; }

11 Solution 11 To avoid the "drop- through" behavior, we need to add a _________ To avoid the "drop- through" behavior, we need to add a _________ or ____________ statement at the end of each case: switch(dayNumber) { case 1: cout << "Sunday"; break; case 2: cout << "Monday"; break; case 3: cout << "Tuesday"; break; case 4: cout << "Wednesday"; break; case 5: cout << "Thursday"; break; case 6: cout << "Friday"; break; case 7: cout << "Saturday"; break; default: cout << "Error!" << endl; } Output when is 6? _______________ Output when dayNumber is 6? _______________

12 Other Repetition Structures count = first count <= last Statement count++ F T 12 The most common use of for loops is to count from one value first to another value last: for (int count = first; count <= last; count++) Statement Or to count down from a larger value to a smaller one: for (int count = first; count >= last; count--) Statement

13 More General Loops 13 For example, in the structure pictured at the right, repetition continues so long as some Condition is true. But sometimes — e.g., when reading data — we need a more general repetition structure  one in which we don't know in advance how many iterations will be needed. StatementList 1 Condition T F StatementList 2

14 The while Loop For such situations, C++ provides the while loop: while (Condition) Statement Condition T F Statement Statement is almost always a compound C++ statement. Repetition continues while Condition is true. 14

15 Post-test Loops If StatementList 2 is omitted in our general repetition structure, we get a test-at-the-__________ or ___________ loop. 15 Condition TF StatementList 1

16 The do Loop For such situations, C++ provides the do loop: do Statement while (Condition); Condition TF Statement 16 Statement is almost always a compound C++ statement. Repetition "does" Statement while Condition is true. NOTE!

17 The do-loop is good for query-controlled input loops: do { cout << "\nEnter a failure time: "; cin >> failureTime; failureTimeSum += failureTime; numComponents++; cout << "Do you have more data to enter (y or n)? "; cin >> response; } while (response == 'y' || response == 'Y'); 17 The do-loop is good for fool-proofing input loops:do{ Prompt for a menu selection and have the user enter it Prompt for a menu selection and have the user enter it} while ( not a valid menu selection ); Could use in main( ) of Proj. 6

18 More general loops like that pictured earlier in which the termination test is made neither at the top nor the bottom of the loop are sometimes called test-in-the-middle loops. Note: The"T" and "F" labels on Condition have been switched here so that repetition terminates when Condition becomes true. This makes it easier to implement this structure. StatementList 1 Condition F T StatementList 2 Test-in-the-Middle Loops 18

19 Such test-in-the-middle loops can be implemented in C++ with a for-loop of the form: for (;;) { StatementList 1 if (Condition) break; StatementList 2 } StatementList 1 Condition F T StatementList 2 Because the for clause contains no expressions to control repetition (thus allowing an infinite loop), this is sometimes called a _______________. // or while (true) Forever Loops 19

20 The forever loop is very useful for constructing sentinel-controlled input loops: for (;;) { Input dataValue ________________________________________ Process dataValue } Note that when the sentinel value is input, it does not get processed as a "regular" data value. Also note that if the sentinel value is the first value entered, repetition terminates immediately. // or while (true) Test-in-the-Middle Input Loops 20 Good to set off termination test with blank line before and after it.

21 // Read, count, find mean of a list of numbers int count = 0; double value, sum = 0, mean; for (;;) { cout > value; _______________________________________ count++; sum += value; } if (count == 0) cerr << "No values entered\n"; else mean = sum / count; An Example 21

22 Summary C++ provides four repetition statements: The for loop, for counting. The while loop, a general-purpose pretest loop. The do loop, a general-purpose post-test loop. The forever loop, a general-purpose test-in- the-middle loop. 22

23 The four C++ loops provide very different behaviors: The for loop is a loop designed for counting that provides pretest behavior. The while loop is a general-purpose loop that provides test-at-the-top (pretest) behavior. The do loop is a general-purpose loop that provides test-at-the-bottom (post-test) behavior. The forever loop is a general-purpose loop that provides test-in-the-middle behavior. 23

24 Choosing a Loop: Use the for loop for problems that require counting over some range of values. For other problems, identify the condition needed to terminate repetition and then determine whether execution needs to:use a: skip the loop body if terminationwhile loop condition doesn't hold go through the body at leastdo loop once before checking termination condition go through the first part of loop forever loop body before checking termination condition and skip second part if it holds 24


Download ppt "1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)"

Similar presentations


Ads by Google