Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

34
Chapter 5 Chapter 5 Selection Statements Selection Statements Mr. Dave Clausen Mr. Dave Clausen La Cañada High School La Cañada High School

Transcript of Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Page 1: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Chapter 5Chapter 5Selection StatementsSelection Statements

Mr. Dave ClausenMr. Dave Clausen

La Cañada High SchoolLa Cañada High School

Page 2: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

ObjectivesObjectives

Construct and evaluate Boolean expressions Understand how to use selection statements

to make decisions Design and test if statements Design and test if-else statements Design and test switch statements

Dave Clausen 2

Page 3: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 3

Boolean ExpressionsBoolean Expressions

Selection StatementsSelection Statements– a control statement that help the computer make a control statement that help the computer make

decisionsdecisions– Certain code is executed when the condition is Certain code is executed when the condition is

true, other code is executed or ignored when the true, other code is executed or ignored when the condition is false.condition is false.

Control StructureControl Structure– controls the flow of instructions that are controls the flow of instructions that are

executed.executed.

Page 4: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 4

New Data TypeNew Data Type

Simple data types that we already knowSimple data types that we already know– int, double, charint, double, char

New simple typeNew simple type– bool (Boolean data type: bool (Boolean data type: truetrue or or falsefalse))

– bool is_prime = bool is_prime = falsefalse;;

– if (is_prime = = if (is_prime = = truetrue) //not necessary to test) //not necessary to test

– if (is_prime) //preferred: is_prime contains true of falseif (is_prime) //preferred: is_prime contains true of false

Page 5: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 5

Boolean Data TypeBoolean Data Type In older systemsIn older systems

– 0 represents false0 represents false– the number 1 represents truethe number 1 represents true– assign values of assign values of truetrue or or falsefalse in lowercase letters in lowercase letters

BOOLTEST_Dev.cpp

Page 6: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 6

Relational Operators, and Relational Operators, and Boolean ExpressionsBoolean Expressions

Relational OperatorsRelational Operators– operations used on same data types for operations used on same data types for

comparisoncomparison equality, inequality, less than, greater thanequality, inequality, less than, greater than

Simple Boolean ExpressionSimple Boolean Expression– two values being compared with a single two values being compared with a single

relational operatorrelational operator– has a value of has a value of truetrue or or falsefalse

Page 7: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 7

Relational OperatorsRelational OperatorsArithmeticArithmetic

OperationOperation=

<

>

RelationalOperator= =<><=>=!=

Meaning

Is equal toIs less than

Is greater thanless than or equal to

greater than or equal toIs not equal to

Page 8: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 8

Simple Boolean ExpressionsSimple Boolean Expressions

7 = = 77 = = 7

-3.0 = = 0.0-3.0 = = 0.0

4.2 > 3.74.2 > 3.7

-18 < -15-18 < -15

13 < 0.01313 < 0.013

-17.32 != -17.32-17.32 != -17.32

a = = aa = = a

truetrue

falsefalse

truetrue

truetrue

falsefalse

falsefalse

truetrue

Page 9: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 9

Order of OperationsOrder of Operations

1. ( )1. ( )

2. *, /, %2. *, /, %

3. +, -3. +, -

4. = =, <, >, <=, >=, !=4. = =, <, >, <=, >=, !=

Page 10: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 10

Comparing StringsComparing Strings

Compared according to ASCII valuesCompared according to ASCII values– upper case < lower case (i.e. ‘A’ < ‘a’ is true)upper case < lower case (i.e. ‘A’ < ‘a’ is true)

When comparing 2 strings where one is a When comparing 2 strings where one is a subset of the other (one string is shorter & subset of the other (one string is shorter & contains all the same letters)contains all the same letters)– shorter string < longer stringshorter string < longer string– i.e. “Alex” < “Alexander”i.e. “Alex” < “Alexander”

Page 11: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 11

Confusing = and = =Confusing = and = =

= = means equality in a comparison= = means equality in a comparison = means assigning a value to an identifier= means assigning a value to an identifier side effects are caused if we confuse the side effects are caused if we confuse the

two operatorstwo operators

P209EX1Dev.cpp

Page 12: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 12

Compound Boolean ExpressionsCompound Boolean Expressions

Logical OperatorsLogical Operators– And && (two ampersands) ConjunctionAnd && (two ampersands) Conjunction– Or || (two pipe symbols) DisjunctionOr || (two pipe symbols) Disjunction– Not ! (one exclamation point) NegationNot ! (one exclamation point) Negation

Use parentheses for each simple expression Use parentheses for each simple expression and the logical operator between the two and the logical operator between the two parenthetical expressions.parenthetical expressions.– i.e. ((grade >= 80) && (grade < 90)) i.e. ((grade >= 80) && (grade < 90))

Page 13: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 13

Truth Tables for AND / ORTruth Tables for AND / OR

Expression1Expression1 Expression2Expression2 E1&&E2E1&&E2 E1||E2E1||E2

(E1)(E1) (E2)(E2)

truetrue truetrue truetrue truetrue

truetrue falsefalse falsefalse truetrue

falsefalse truetrue falsefalse truetrue

falsefalse falsefalse falsefalse falsefalse

Page 14: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 14

Truth Table for NOTTruth Table for NOTOrder of Priority for BooleansOrder of Priority for Booleans

ExpressionExpression Not ENot E

(E)(E) !E!E

truetrue falsefalse

falsefalse truetrue Order Of Priority in Boolean ExpressionsOrder Of Priority in Boolean Expressions

– 1. !1. !– 2. &&2. &&– 3. ||3. ||

Page 15: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 15

Order of Operations including Order of Operations including BooleansBooleans

1. ( )1. ( ) 2. !2. ! 3. *, /, %3. *, /, % 4. +, -4. +, - 5. <, <=, >, >=, = =, !=5. <, <=, >, >=, = =, != 6. &&6. && 7. ||7. ||

Page 16: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 16

ComplementsComplements

OperationOperation

! <! < ! <=! <= ! >! > ! >=! >=

Complement Complement (equivalent) (equivalent)

>=>= >> <=<= <<

Page 17: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 17

DeMorgan’s LawsDeMorgan’s Laws

! ( A && B) is the same as: !A || !B! ( A && B) is the same as: !A || !B Not (true AND true) Not(true) OR Not(true) Not (true AND true) Not(true) OR Not(true)

Not (true) false OR false Not (true) false OR false

false falsefalse false

!( A || B) is the same as: !A && !B!( A || B) is the same as: !A && !B

Not( true OR true) Not(true) AND Not(true)Not( true OR true) Not(true) AND Not(true)

Not (true) false AND falseNot (true) false AND false

false falsefalse false

Page 18: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 18

If StatementsIf Statements Format for if statements:Format for if statements:

if (<Boolean expression>)if (<Boolean expression>) <statement><statement>– Parentheses are Parentheses are requiredrequired around the Boolean around the Boolean

Expression.Expression.sum = 0.0;um = 0.0;

cin>>number;cin>>number;if (number > 0.0)if (number > 0.0) sum = sum + number;sum = sum + number;cout<<“the sum is: “<<sum<<endl;cout<<“the sum is: “<<sum<<endl;

Page 19: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 19

Compound StatementsCompound Statements– Use the symbols { and } to group several Use the symbols { and } to group several

statements as a single unit.statements as a single unit.– Simple statements within the compound Simple statements within the compound

statements end with semicolons.statements end with semicolons.– Compound Statements are sometimes called a Compound Statements are sometimes called a

statement block.statement block.– Use compound statements in an if statement if Use compound statements in an if statement if

you want several actions executed when the you want several actions executed when the Boolean expression is true.Boolean expression is true. MINMAXDev.cpp

Page 20: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 20

if …else Statementsif …else Statements Format for if…else statementsFormat for if…else statements

if (<Boolean expression>)if (<Boolean expression>){{ <true statement><true statement> //end of if option//end of if option}}elseelse{{ <false statement><false statement> //end of else option//end of else option}}

Page 21: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 21

if …else Exampleif …else Examplecout<<“Please enter a number and press <Enter>. “;cout<<“Please enter a number and press <Enter>. “;

cin>>number;cin>>number;

if (number < 0)if (number < 0)

{{

neg_count = neg_count + 1;neg_count = neg_count + 1;

cout<<setw(15) << number<<endl;cout<<setw(15) << number<<endl;

//end if option//end if option

}}

elseelse

{{

non_neg_count = non_neg_count + 1;non_neg_count = non_neg_count + 1;

cout << setw(30) << number << endl;cout << setw(30) << number << endl;

//end of else option//end of else option

}}

Page 22: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 22

Behavior of Selection StatementsBehavior of Selection Statements

?

statement

true

?

statement

false

true

false

statement

if (<Boolean expression>){ <statement 1> . <statement n>}

if (<Boolean expression>) <statement>else{ <statement 1> . <statement n>}

Page 23: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 23

Robust ProgramsRobust Programs

Robust Programs are protected from: Robust Programs are protected from: – most possible crashesmost possible crashes– bad databad data– unexpected valuesunexpected values

For student programsFor student programs– balance “error trapping” and code efficiencybalance “error trapping” and code efficiency– our text assumes valid data is entered when our text assumes valid data is entered when

requested.requested.

Page 24: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 24

Nested if statementsNested if statements Nested if statement Nested if statement (avoid this for this class)(avoid this for this class)

– an if statement used within another if statement an if statement used within another if statement where the “true” statement or action is.where the “true” statement or action is.

if (score >=50)if (score >=50)

if (score>=69.9)if (score>=69.9)

cout<<blah, blah, blahcout<<blah, blah, blah //true for score>=69.9 and score>=50//true for score>=69.9 and score>=50

elseelse

cout<<blah, blah, blahcout<<blah, blah, blah //false score>=69.9 true score >=50//false score>=69.9 true score >=50

elseelse

cout<<blah, blah, blahcout<<blah, blah, blah //false for score >=50//false for score >=50

Page 25: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 25

Extended if statementsExtended if statements

– Extended if statements are Nested if statements Extended if statements are Nested if statements where another if statement is used with the else where another if statement is used with the else clause of the original if statement. clause of the original if statement. (use this for this (use this for this class)class)

if (condition 1)if (condition 1) action1action1else if (condition2)else if (condition2) action2action2

elseelse action3action3

Page 26: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 26

Avoid Sequential SelectionAvoid Sequential Selection

This is not a good programming practice.This is not a good programming practice.– Less efficientLess efficient– only one of the conditions can be trueonly one of the conditions can be true

this is called mutually exclusive conditionsthis is called mutually exclusive conditions

if (condition1)if (condition1) //avoid this structure//avoid this structure

action1action1 //use nested selection//use nested selection

if (condition2)if (condition2)

action2action2

if (condition3)if (condition3)

action3action3

SALESDev.cpp

Page 27: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 27

Program TestingProgram Testing

Use test data that tests every branch or Use test data that tests every branch or selection in the program.selection in the program.

Test the if statement(s)Test the if statement(s) Test the else statement(s)Test the else statement(s) Test the border, edge, extreme cases.Test the border, edge, extreme cases. Test carefully nested and extended selection Test carefully nested and extended selection

statements and their paths.statements and their paths.

Page 28: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 28

Switch StatementsSwitch Statements Allows for multiple selection that is easier to Allows for multiple selection that is easier to

follow than nested or extended if statements.follow than nested or extended if statements.

switch (age)switch (age) ////age is of type intage is of type int

{{

case 18:case 18: <statement1><statement1>

break;break;

case 19:case 19: <statement2><statement2>

break;break;

case 20:case 20: <statement3><statement3>

break;break;

default:default: <default statement><default statement>

}}

Page 29: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 29

Switch: Flow of ExecutionSwitch: Flow of Execution– The selector (argument) for switch must be of an The selector (argument) for switch must be of an

ordinal type (not double)ordinal type (not double) switch (age)switch (age) The variable “age” is called the selector in our The variable “age” is called the selector in our

example.example. If the first instance of the variable is found among the If the first instance of the variable is found among the

labels, the statement(s) following this value is executed labels, the statement(s) following this value is executed until reaching the next break statement.until reaching the next break statement.

Program control is then transferred to the next Program control is then transferred to the next statement following the entire switch statement.statement following the entire switch statement.

If no value is found, the default statement is executed.If no value is found, the default statement is executed.

Page 30: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 30

Switch Statement Example 2Switch Statement Example 2switch (grade)switch (grade) //grade is of type char//grade is of type char

{{

case ‘A’ :case ‘A’ :

case ‘B’ :case ‘B’ : cout<<“Good work!”<<endl;cout<<“Good work!”<<endl;

break;break;

case ‘C’ :case ‘C’ : cout<<“Average work”<<endl;cout<<“Average work”<<endl;

break;break;

case ‘D’ :case ‘D’ :

case ‘F’ :case ‘F’ : cout<<“Poor work”<<endl;cout<<“Poor work”<<endl;

break;break;

default :default :cout<<grade<<“ is not a valid letter grade.”;cout<<grade<<“ is not a valid letter grade.”;

break;break;

}}

Page 31: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 31

AssertionsAssertions– AssertionsAssertions

A statement about what we expect to be true at a certain A statement about what we expect to be true at a certain point in the program where the assertion is placed.point in the program where the assertion is placed.

Could be used with selection, functions, and repetition Could be used with selection, functions, and repetition to state what you expect to happen when certain to state what you expect to happen when certain conditions are true.conditions are true.

Could be comments, should be Boolean expressions Could be comments, should be Boolean expressions that could be evaluated by the compiler.that could be evaluated by the compiler.

Are used as preconditions and post conditionsAre used as preconditions and post conditions Can be used as a proof of your program’s correctnessCan be used as a proof of your program’s correctness Can help you “debug” your program. If there is an Can help you “debug” your program. If there is an

error, the program halts with an error message and the error, the program halts with an error message and the line number where the error is located.line number where the error is located.

Page 32: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 32

Implementing AssertionsImplementing Assertions Use #include <cassert>Use #include <cassert>

– Example 1:Example 1:assert (number_of_students != 0);assert (number_of_students != 0);

class_average = sum_of_scores / number_of_students;class_average = sum_of_scores / number_of_students;

– The parameter of assert is a Boolean Expression.The parameter of assert is a Boolean Expression.– The compiler verifies if the assertion is true or The compiler verifies if the assertion is true or

falsefalse if false, the program halts with an error message:if false, the program halts with an error message:

Assertion Failed: number_of_students !=0, file Assertion Failed: number_of_students !=0, file “filename”, line 48“filename”, line 48

this tells you that your assertion is falsethis tells you that your assertion is false

Page 33: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 33

Assertion Example #2Assertion Example #2

Assertions used as pre & post conditions:Assertions used as pre & post conditions:

assert((num1>=0) && (num2>=0)); //preconditionassert((num1>=0) && (num2>=0)); //precondition

if (num1 < num2)if (num1 < num2)

{{

temp = num1;temp = num1;

num1 = num2;num1 = num2;

num2 = temp;num2 = temp;

}}

assert((num1>=num2) && (num2>=0)); //postconditionassert((num1>=num2) && (num2>=0)); //postcondition

Page 34: Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Dave Clausen 34

Assert as a Debugging ToolAssert as a Debugging Tool Executable assertions when false, terminate your Executable assertions when false, terminate your

program and tell you the line number where the error is program and tell you the line number where the error is located.located.

This is valuable during the software debugging and This is valuable during the software debugging and testing phases.testing phases.

When your program is working correctly, you do not When your program is working correctly, you do not need to remove all the assertions manually.need to remove all the assertions manually.

Add the preprocessor directive:Add the preprocessor directive:

#define NDEBUG #define NDEBUG BEFOREBEFORE

#include <cassert>#include <cassert> to ignore all assert functions.to ignore all assert functions.

//NDEBUG means No debug.//NDEBUG means No debug.assertDev.cpp