1 more control structures if and switch (chap. 8) do-while and forever loops (chap. 9)

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

Upload: vincent-holland

Post on 13-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

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

1

More Control Structures

if and switch(Chap. 8)

do-while and forever loops (Chap. 9)

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

Are there any WeaknessesAre there any Weaknessesin the in the ifif Statement? Statement?

For some problems, the "waterfall" For some problems, the "waterfall" execution of the multi-branch execution of the multi-branch ifif leads to leads to poor (or perhaps unacceptable) poor (or perhaps unacceptable) performance of a program.performance of a program.

Example: Suppose we need a function Example: Suppose we need a function that, given the number of a day of the that, given the number of a day of the week (1-7), computes its corresponding week (1-7), computes its corresponding name (Sunday-Saturday)?name (Sunday-Saturday)?

2

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

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

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

// Receive a day number, return its namestring 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

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

The multi-branch The multi-branch ifif has has ____________________________________________ time:time:

• Computing "Sunday" requires ___ comparisonComputing "Sunday" requires ___ comparison

• Computing "Monday" requires ___ comparisonsComputing "Monday" requires ___ comparisons

• ......

• Computing "Saturday" requires ___ comparisonsComputing "Saturday" requires ___ comparisons

Computations that are "later" in the Computations that are "later" in the ifif take take longer.longer.

There are situations where the time to select one There are situations where the time to select one of many statements must be ________________.of many statements must be ________________.

5

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

A SolutionA SolutionThe 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.

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

The switch StatementThe 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

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

8

Pattern:

switch (expression) { caseList1

StatementList1

caseList2 StatementList2

... caseListN

StatementListN

default:StatementListN+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.

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

WarningWarning

C++ switch statements exhibit C++ switch statements exhibit ________________ ________________ behaviorbehavior. .

1. 1. expressionexpression is evaluated. is evaluated.

2. If 2. If expressionexpression == == constantconstanti i , control jumps to the , control jumps to the StatementStatement associated with associated with constantconstantii..

3. Control continues 3. Control continues ____________________________ the switch statement until:until:a. The end of the switch is reached;a. The end of the switch is reached;b. A b. A break is executed, terminating the switch; is executed, terminating the switch;c. A c. A return is executed, terminating the function; or is executed, terminating the function; ord. An d. An exit() is executed, terminating the program. is executed, terminating the program. 9

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

Output: ______________________________Output: ______________________________ 10

ExampleExampleWhat will the following statement display, What will the following statement display, if the value of if the value of dayNumber is 6? 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;}

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

SolutionSolution

11

To avoid the "drop-To avoid the "drop-through" behavior, we through" behavior, we need to add a _________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 Output when dayNumber is 6? _______________ is 6? _______________

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

Other Repetition Other Repetition StructuresStructures

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

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

More General LoopsMore 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.

StatementList1

Condition

T

F

StatementList2

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

The while LoopThe while LoopFor such situations, C++ provides the while loop:

while (Condition) Statement

Condition

T

F

StatementStatement is almost always a compound C++ statement.

Repetition continues while Condition is true.

14

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

Post-test LoopsPost-test Loops

If StatementList2 is omitted in our general repetition structure, we get a test-at-the-__________ or ___________ loop.

15

Condition TF

StatementList1

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

The do LoopThe do LoopFor such situations, C++ provides the do loop:do Statementwhile (Condition);

Condition TF

Statement

16

Statement is almost always a compound C++ statement.

Repetition "does" Statement while Condition is true.

NOTE!

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

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:

dodo{{     Prompt for a menu selection and have the user enter itPrompt for a menu selection and have the user enter it}}while ( while ( not a valid menu selection not a valid menu selection ););

Could use in main( ) of Proj. 6

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

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.

StatementList1

Condition

F

T

StatementList2

Test-in-the-Middle LoopsTest-in-the-Middle Loops

18

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

Such test-in-the-middle loops can be implemented in C++ with a for-loop of the form:

for (;;){StatementList1

if (Condition) break; StatementList2}

StatementList1

Condition

F

T

StatementList2

Because the for clause containsno expressions to control repetition (thus allowing an infinite loop), this is sometimes called a _______________.

// or while (true)

Forever LoopsForever Loops

19

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

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 Test-in-the-Middle Input LoopsLoops

20

Good to set off

terminationtest with blank line

before and after it.

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

// Read, count, find mean of a list of numbersint count = 0;double value, sum = 0, mean;for (;;){ cout << "Enter next value (-999 to stop): "; cin >> value;

_______________________________________

count++; sum += value;}

if (count == 0) cerr << "No values entered\n";else mean = sum / count;

An ExampleAn Example

21

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

SummarySummary

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

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

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

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

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 termination while loopcondition doesn't hold

go through the body at least do looponce before checking termination condition

go through the first part of loop forever loopbody before checking termination condition and skip second part if it holds

24