38
Calvin College [email protected] Controlling Behavior Controlling Behavior The if, switch and for Statements

Calvin College Controlling Behavior The if, switch and for Statements

Embed Size (px)

DESCRIPTION

Sequential execution C++ statements are executed one after another (or in sequence) by default: { Statement 1 Statement 2... Statement N } The C++ compound statement (or block) can be thought of as a statement for eliciting sequential execution of a series of statements.

Citation preview

Page 1: Calvin College Controlling Behavior The if, switch and for Statements

Calvin College •[email protected]

Controlling BehaviorControlling BehaviorThe if, switch and for Statements

Page 2: Calvin College Controlling Behavior The if, switch and for Statements

Function BehaviorFunction BehaviorThe behavior of a function is determined by The behavior of a function is determined by

the statements within the function.the statements within the function.Statements fall into one of three categories:Statements fall into one of three categories:• Statements that simply execute in sequence.Statements that simply execute in sequence.• Statements that select one of several Statements that select one of several

alternatives.alternatives.• Statements that repeat another statement.Statements that repeat another statement.

Page 3: Calvin College Controlling Behavior The if, switch and for Statements

Sequential executionSequential executionC++ statements are executed one after C++ statements are executed one after

another (or in sequence) by default:another (or in sequence) by default:{ Statement1

Statement2

... StatementN

}

The C++ The C++ compound statementcompound statement (or (or blockblock) can be ) can be thought of as a statement for eliciting thought of as a statement for eliciting sequential execution of a series of statements.sequential execution of a series of statements.

Page 4: Calvin College Controlling Behavior The if, switch and for Statements

Selective ExecutionSelective ExecutionBy contrast, there are situations in which a problem’s By contrast, there are situations in which a problem’s

solution requires that a statement be executed solution requires that a statement be executed selectivelyselectively, based on a , based on a conditioncondition (a boolean expression): (a boolean expression):

if (Condition) Statement1

[ else Statement2 ]

The C++ The C++ if statementif statement is a statement for eliciting selective is a statement for eliciting selective execution of a statement, allowing a program to choose execution of a statement, allowing a program to choose to execute either to execute either StatementStatement11 or or StatementStatement22, but not both., but not both.

Page 5: Calvin College Controlling Behavior The if, switch and for Statements

The Simple ifThe Simple ifThe C++ if statement has several different forms.The C++ if statement has several different forms.The first form has no The first form has no else or or StatementStatement22, and is , and is

called the called the simple ifsimple if::

if (Condition) Statement

If If ConditionCondition is true, is true, StatementStatement is executed; is executed; otherwise otherwise StatementStatement is skipped. is skipped.

Condition

Statement

T

F

Page 6: Calvin College Controlling Behavior The if, switch and for Statements

The Two-Branch ifThe Two-Branch ifIn the second form of if, the In the second form of if, the else and and

StatementStatement22 are present: are present:

if (Condition) Statement1

else Statement2

If If ConditionCondition is true, is true, StatementStatement11 is executed and is executed and StatementStatement22 is skipped; otherwise is skipped; otherwise StatementStatement11 is is skipped and skipped and StatementStatement22 is executed. is executed.

Condition

Statement1

T F

Statement2

Page 7: Calvin College Controlling Behavior The if, switch and for Statements

The Multi-branch ifThe Multi-branch ifThe if’s final form has a nested if as The if’s final form has a nested if as StatementStatement22::

if (Cond1) Stmt1

else if (Cond2) Stmt2

... else if (CondN) StmtN

else StmtN+1

Cond1

Stmt1

T F

Stmt2

Cond2T F

StmtN

CondNT F

StmtN+1

. . .

Page 8: Calvin College Controlling Behavior The if, switch and for Statements

Multibranch if BehaviorMultibranch if BehaviorIf If ConditionCondition11 is true, is true, StatementStatement11 is executed and is executed and

the remaining statements are skipped; the remaining statements are skipped; otherwise, control moves to otherwise, control moves to ConditionCondition22; ; if if ConditionCondition22 is true, is true, StatementStatement22 is executed is executed and the remaining statements are skipped; and the remaining statements are skipped; otherwise control goes to the next condition otherwise control goes to the next condition ... ... if if ConditionConditionNN is true is true StatementStatementNN is executed is executed and and StatementStatementN+1N+1 is skipped; is skipped; otherwise, otherwise, StatementStatementN+1N+1 is executed. is executed.

Page 9: Calvin College Controlling Behavior The if, switch and for Statements

Multibranch ifMultibranch ifThis form is useful when you must select one This form is useful when you must select one

of several alternatives: of several alternatives: if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; ... else if (score >= 60) grade = ‘D’; else grade = ‘F’;

Page 10: Calvin College Controlling Behavior The if, switch and for Statements

C++ StatementsC++ StatementsNote that a Note that a StatementStatement can be either a single can be either a single

statement, or a compound statement:statement, or a compound statement: if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’;

If you need to select two or more statements, If you need to select two or more statements, they must bethey must be wrapped in curley-braces wrapped in curley-braces to form a compound statement.to form a compound statement.

Page 11: Calvin College Controlling Behavior The if, switch and for Statements

Using SelectionUsing SelectionSelection is useful anytime you want to Selection is useful anytime you want to

execute a statement under particular execute a statement under particular circumstances.circumstances.

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)?

Page 12: Calvin College Controlling Behavior The if, switch and for Statements

AlgorithmAlgorithm0. Receive dayNumber.0. Receive dayNumber.1. If dayNumber == 1:1. If dayNumber == 1:

Return “Sunday”.Return “Sunday”.Else if dayNumber == 2:Else if dayNumber == 2:Return “Monday”.Return “Monday”.

Else if dayNumber == 3:Else if dayNumber == 3:Return “Tuesday”.Return “Tuesday”.

Else if dayNumber == 4:Else if dayNumber == 4:Return “Wednesday”.Return “Wednesday”.

Else if dayNumber == 5:Else if dayNumber == 5:Return “Thursday”.Return “Thursday”.

Else if dayNumber == 6:Else if dayNumber == 6:Return “Friday”.Return “Friday”.

Else if dayNumber == 7:Else if dayNumber == 7:Return “Saturday”.Return “Saturday”.

Else Else Display an error message, and return “”.Display an error message, and return “”.

Page 13: Calvin College Controlling Behavior The if, switch and for Statements

Coding 1Coding 1Such an algorithm can be coded using a multi-Such an algorithm can be coded using a multi-

branch if:branch if: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 “”; }}

Page 14: Calvin College Controlling Behavior The if, switch and for Statements

DrawbackDrawbackThe multi-branch if has The multi-branch if has non-uniform executionnon-uniform execution time: time:• Computing “Sunday” requires 1 comparisonComputing “Sunday” requires 1 comparison• Computing “Tuesday” requires 2 comparisonsComputing “Tuesday” requires 2 comparisons• ......• Computing “Saturday” requires 7 comparisonsComputing “Saturday” requires 7 comparisonsComputations that are “later” in the if take Computations that are “later” in the if take

longer.longer.There are situations where the time to select one of There are situations where the time to select one of

many statements must be many statements must be uniformuniform..

Page 15: Calvin College Controlling Behavior The if, switch and for Statements

A SolutionA SolutionThe C++ switch statement provides an alternative:The C++ switch statement provides an alternative:string DayName(int dayNumber){ switch (dayNumber) { case 1: return “Sunday”; case 2: return “Monday”; case 3: return “Tuesday”; case 4: return “Wednesday”; case 5: return “Thursday”; case 6: return “Friday”; case 7: return “Saturday”; default: cerr << “\n* DayName: invalid day number\n”; return “”; }}

Page 16: Calvin College Controlling Behavior The if, switch and for Statements

The switch StatementThe switch StatementThe switch statement provides multi-branch The switch statement provides multi-branch

selection, but guarantees selection, but guarantees uniform execution uniform execution timetime, regardless of which branch is selected., regardless of which branch is selected.

Thus, the time to selectThus, the time to select return “Saturday”;return “Saturday”;

is identical to the time to selectis identical to the time to select return “Sunday”;return “Sunday”;

if a switch statement is used to select them.if a switch statement is used to select them.

Page 17: Calvin College Controlling Behavior The if, switch and for Statements

The switch Statement (ii)The switch Statement (ii)Pattern:Pattern: switch (Expression) { caseList1 StatementList1

caseList2 StatementList2

... caseListN StatementListN

default: StatementListN+1 }

where where ExpressionExpression is an integer-compatible expression, is an integer-compatible expression, each each caseListcaseList is one or more is one or more casescases of this form: of this form:

case ConstantValue :

and each and each StatementListStatementList usually ends with a usually ends with a break or or return statement. statement.

Page 18: Calvin College Controlling Behavior The if, switch and for Statements

ExampleExampleSwitch statements can use any Switch statements can use any integer-compatible typeinteger-compatible type::

double StraightPercentageCutOff(char letterGrade){ switch(letterGrade) { case ‘A’: return 90.0; case ‘B’: return 80.0; case ‘C’: return 70.0; case ‘D’: return 60.0; case ‘F’: return 0.0; default: cerr << “\n** Invalid letter grade: “ << letterGrade << “ received by StraightPercentageCutOff” << endl; exit(1); } }

They They cannotcannot be used with be used with string or or double values: values:

Page 19: Calvin College Controlling Behavior The if, switch and for Statements

Another RestrictionAnother Restriction

If (Variable == Constant1) Statement1

Else if (Variable == Constant2) Statement2

...Else if (Variable == ConstantN) StatementN

Else StatementN+1

To use the switch, the common algorithm To use the switch, the common algorithm pattern ispattern is:

switch (Variable){ case Constant1:

StatementList1

case Constant2: StatementList2

... case ConstantN:

StatementListN

default: StatementListN+1

}

Page 20: Calvin College Controlling Behavior The if, switch and for Statements

WarningWarningC++ switch statements exhibit C++ switch statements exhibit drop-through behaviordrop-through behavior. .

1. 1. ExpressionExpression is evaluated. is evaluated.

2. If 2. If ExpressionExpression == == ConstantValueConstantValueii: Control : Control jumps to the jumps to the StatementStatement after after ConstantValueConstantValueii..

3. Control continues 3. Control continues within the switch statementwithin 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.

Page 21: Calvin College Controlling Behavior The if, switch and for Statements

ExampleExampleWhat will the following function display, What will the following function display,

if the value of if the value of dayNumber is 3? is 3?

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;}

Output: Output: TuesdayWednesdayThursdayFridaySaturdayError!

Page 22: Calvin College Controlling Behavior The if, switch and for Statements

SolutionSolutionTo avoid the “drop-though” behavior, we need to To avoid the “drop-though” behavior, we need to

add a add a break statement at the end of each case: 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 == 3: == 3: Tuesday

Page 23: Calvin College Controlling Behavior The if, switch and for Statements

DifficultyDifficultyThere are other operations that are difficult There are other operations that are difficult

to implement, using just sequential to implement, using just sequential execution.execution.

Example: Let’s write a program to read in a Example: Let’s write a program to read in a sequence of test scores, and display their sequence of test scores, and display their average and a corresponding pass/fail average and a corresponding pass/fail grade.grade.

Page 24: Calvin College Controlling Behavior The if, switch and for Statements

Repetitive ExecutionRepetitive ExecutionFinally, there are situations where solving a problem requires Finally, there are situations where solving a problem requires

that a statement be that a statement be repeatedrepeated, with the repetition being , with the repetition being controlled by a controlled by a conditioncondition::

for (InitializerExpr; LoopCondition; IncrementExpr) Statement

The C++ The C++ for statementfor statement is a statement for eliciting is a statement for eliciting repetitive execution of a statement, allowing a repetitive execution of a statement, allowing a program to repeat the execution of program to repeat the execution of StatementStatement..

Page 25: Calvin College Controlling Behavior The if, switch and for Statements

The for LoopThe for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement

StatementStatement will be will be executed so long as executed so long as LoopConditionLoopCondition is true. is true.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

StatementStatement is often is often called the called the bodybody of the of the loop.loop.

Page 26: Calvin College Controlling Behavior The if, switch and for Statements

The for LoopThe for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement

Each execution ofEach execution of LoopCondition, LoopCondition, Statement, Statement, IncrementExpr IncrementExpr is called one is called one repetitionrepetition or or iterationiteration of the loop. of the loop.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

Page 27: Calvin College Controlling Behavior The if, switch and for Statements

The for LoopThe for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement

WhenWhen LoopCondition LoopCondition becomes false,control becomes false,control proceeds to the next proceeds to the next statement.statement.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

Note: if theNote: if the LoopCondition LoopCondition is initially false, then is initially false, then the body of the loop will the body of the loop will not be executed.not be executed.

Page 28: Calvin College Controlling Behavior The if, switch and for Statements

CountingCountingThe “normal” use of the for loop is to The “normal” use of the for loop is to countcount:: for (int count = 1; count <= limit; count++) cout << count << endl;

Output (suppose limit == 7):Output (suppose limit == 7): 1 2 3 4 5 6 7

Page 29: Calvin College Controlling Behavior The if, switch and for Statements

Nested LoopsNested LoopsLoops can also be Loops can also be nestednested:: for (int val1 = 1; val1 <= limit1; val1++) for (int val2 = 1; val2 <= limit2; val2++) cout << val1 << ‘*’ val2 “ = “ << val1 * val2 << endl;

1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6

Output (suppose limit1 == 2, limit2 == 3):Output (suppose limit1 == 2, limit2 == 3):

Page 30: Calvin College Controlling Behavior The if, switch and for Statements

Counting LoopsCounting LoopsAs we have indicated, the for loop is normally As we have indicated, the for loop is normally

used to count through a range of values:used to count through a range of values: for (int count = first; count <= last; count++) Statement

Such a loop will count from Such a loop will count from firstfirst to to lastlast, , executing executing StatementStatement once for each once for each value in the range value in the range first..lastfirst..last..

Page 31: Calvin College Controlling Behavior The if, switch and for Statements

Noncounting LoopsNoncounting LoopsOne of the quirks of the C++ for loop is One of the quirks of the C++ for loop is

that its three expressions can be omitted:that its three expressions can be omitted: for (;;) { StatementList }

Such a loop will execute infinitely many times, Such a loop will execute infinitely many times, unless statements within unless statements within StatementListStatementList permit execution to leave the loop.permit execution to leave the loop.

Page 32: Calvin College Controlling Behavior The if, switch and for Statements

The forever LoopThe forever LoopWe call such a statement the We call such a statement the forever loopforever loop::Pattern:Pattern:

for (;;) { StatementList1

if (ExitCondition) break;

StatementList2 }

When the if statement is evaluated and When the if statement is evaluated and ExitConditionExitCondition is true, the is true, the break statement statement will execute, terminating the repetition.will execute, terminating the repetition.

Page 33: Calvin College Controlling Behavior The if, switch and for Statements

Forever BehaviorForever Behavior for (;;) { StatementList1

if (ExitCondition) break;

StatementList2 }

StatementList1

ExitCondition

StatementList2

T

FNote: we are guaranteed Note: we are guaranteed

that that StmtList1StmtList1 will will execute at least once, execute at least once, but but StmtList2StmtList2 may not may not execute...execute...

Page 34: Calvin College Controlling Behavior The if, switch and for Statements

Input LoopsInput LoopsThe forever loop is ideal for reading a list The forever loop is ideal for reading a list

of values whose end is marked by a of values whose end is marked by a sentinelsentinel (i.e., an invalid value). (i.e., an invalid value).

Pattern:Pattern: for (;;) { Prompt for value Read value

if (value is the sentinel) break;

Process value }

Page 35: Calvin College Controlling Behavior The if, switch and for Statements

ExampleExample

double ReadAndAverage() { double score, sum = 0.0; int count = 0; for (;;) { cout << “Enter a test score (-1 to quit): “; cin >> score; if (score < 0) break; // test for sentinel count++; sum += score; } if (count > 0) return sum / count; else { cerr << “\n* no scores to average!\n” << endl; exit(1); } }

Read and average a list of test scores:Read and average a list of test scores:

Page 36: Calvin College Controlling Behavior The if, switch and for Statements

Error HandlingError HandlingA forever loop is also useful for fool-proof input.A forever loop is also useful for fool-proof input.Pattern:Pattern: for (;;)

{ Prompt for value Read value

if (value is valid) break;

Display error message }

This is good because control will only leave This is good because control will only leave the loop if/when the user enters a valid the loop if/when the user enters a valid value.value.

Page 37: Calvin College Controlling Behavior The if, switch and for Statements

ExampleExampledouble GetValidDouble(string prompt, double firstValid, double lastValid){ double number; for (;;) { cout << prompt; cin >> number; if (cin.good()) if (number >= firstValid && number <= lastValid) return number; else cout << “\n** Invalid number!\n” << endl; else { cout << “\n** Non-numeric input!\n” << endl; cin.clear(); cin.ignore(80, ‘\n’); } }}

Read a valid number:Read a valid number:

Page 38: Calvin College Controlling Behavior The if, switch and for Statements

SummarySummaryThe C++ compound statement executes The C++ compound statement executes

a block of statements a block of statements sequentiallysequentially..The C++ if statement permits a The C++ if statement permits a

statement to be executed statement to be executed selectivelyselectively, , based on a condition.based on a condition.

The C++ for statement permits a The C++ for statement permits a statement to be executed statement to be executed repeatedlyrepeatedly, , based on a condition.based on a condition.