On completion of this chapter students will learned how to: Create simple if and if-else statements, create relational expressions, utilize logical operators, interpret the order of precedence for all operators (arithmetic, relational, and logical), create multiple decision statements (if-else-if or switch statements), utilize bool data type.
Trang 1Chapter 5 – Decision Making
Trang 2Block of statements done if results true,
skipped if results false!
Trang 5Provides block of statements to be executed for either true OR false
Braces optional if only one statement in block
Trang 6and also when false
True False
Trang 7Three operands needed for proper usage
Conditional ? : operator
– Question mark separates relational expression from rest of statement
– Colon separates two operands
expression1? expression2 : expression3
x = (y < z) ? y : z ;
Lesson 5.2
Trang 8Example: if (a > b) { ans = 10;}
else { ans = 25;}
a > b ? (ans = 10) : (ans = 25) ;
conditional
expression
if true, execute this statement
if false, execute this statement
ans = (a > b) ? 10 : 25 ;
Lesson 5.2
Trang 12Combines two relational expressions
Combined expression true only if BOTH expressions are true
Lesson 5.4
expression1 true && expression2 false false
false && truefalse && falsetrue && true
falsefalsetrue
Trang 13Combines two relational expressions
Combined expression false only if BOTH expressions are false
Lesson 5.4
expression1 true || expression2 false true
false || truefalse || falsetrue || true
truefalsetrue
Trang 15Lesson 5.5
( ) Parentheses L to R 1 ++, Postincrement L to R 2 ++, Preincrement R to L 3 ! Logical NOT L to R 3 +, Positive, negative L to R 3 *, /, % Multiplication, division L to R 4 +, Addition, subtraction L to R 5 <=, >=, >, < Relational operator L to R 6 ==, != Relational operator L to R 7 && Logical AND L to R 8 || Logical OR L to R 9 +=, +, *=, /=, %= Compound assignment R to L 10 = Assignment R to L 10
Trang 18Shifts program control, step by step, through series of statement blocks
Control stops at relational expression that tests true
Lesson 5.6
Trang 20Must result in integer type value
Trang 21 Constant1, constant2, etc must be integer expressions
Constant expressions must
be unique
default optional, used when
no match is found
Trang 22Terminates execution
of switch statementSends control to point
of closing braceUsually last statement for each case
If no break, then statements in next case executed
Trang 23Named after mathematician George BooleCan contain one of only two values (0 or 1)
Trang 25Utilize bool data type
Learned how to: