Tải bản đầy đủ (.pdf) (25 trang)

Lecture Programming in C++ - Chapter 5: Decision making

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (508.04 KB, 25 trang )

Chapter 5 – Decision Making


Simple if Statement
Capable of making decisions
Relational expression evaluated
– Evaluated as true or false

if  (relational expression)
     {
Block of statements 
done if results true,
      statement(s);
skipped if results false!
      }
Lesson 5.1


Relational Expressions
Type of logical expression
– Produces result of true or false

Compares values of two arithmetic 
expressions
left_operand  relational_operator   right_operand

Lesson 5.1


Relational Operators
<


<=
==
>
>=
!=
Lesson 5.1

less than
less than or equal to
equal to
greater than
greater than or equal to
not equal


Simple If/Else Statement
if (expression)
   {
    statement1a;
    statement1b;
    …
    }
if TRUE
else
   {
    statement1a;
    statement1b;
    …
    }
if FALSE

Lesson 5.2

Provides block of 
statements to be executed 
for either true OR false
Braces optional if only 
one statement in block


if  Examples
x = 3;
Simple if – statements only done on true,
if (x < 2)
         but when false, skips to end of if
     {
      cout <<  “x is smaller than 2”;
     }
Full if – code for when true 
and also when false

if  (x < 12)
      cout << “smaller than twelve”
else
      cout  <<  “twelve or larger”;

True 
False 


Ternary Operator

Three 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


Example:

 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



Nested if­else Statements
if (outer)
    { …
        if  (inner)
             { … }
        else
             { … }
    }
else
    { … }
Lesson 5.3

If outer is true,
Executed if inner is true.
this block executed.
Executed if inner is false.
If outer is false,
this block executed.


Three Logical Operators
Exclamation mark  !
– NOT (negation)
– unary

Two ampersands  &&
– AND (conjunction)
– binary


Two vertical pipes  ||

– OR
(inclusive disjunction)
– binary

Lesson 5.4


Logical NOT Operator
Reverses result of relational expression
Example:  ! (x == y)
x
y
73
7
Evaluate relational expression, does 3 equal 7?
7
! ( false ) so negates to true
! ( true ) so negates to false

Lesson 5.4


Logical AND Operator
Combines two relational expressions
Combined expression true only if BOTH 
expressions are true
     true     &&  expression2

     false    
expression1  
false     &&        true
false     &&        false
true      &&        true
Lesson 5.4

false
false
false
true


Logical OR Operator
Combines two relational expressions
Combined expression false only if BOTH 
expressions are false
     true     ||     expression2
     false    
expression1     
false        ||        true
false        ||        false
true         ||        true
Lesson 5.4

true
true
false
true



Values of Relational Expressions
Result of relational expression
– False, C++ compiler gives zero
– True, C++ compiler gives one

Value of relational expression
– Zero, result is false
– Nonzero, result is true
any number other than zero, including negatives
Lesson 5.5


Precedence of Operators
          ( ) 
        ++, ­­
        ++, ­­ 
          !
          +, ­
        *, /, % 
          +, ­
     <=, >=, >, < 
        ==, != 
         &&
           || 
+=, ­+, *=, /=, %=
           = 
Lesson 5.5

Parentheses

    L to R
Postincrement
    L to R
Preincrement
    R to L
Logical NOT
    L to R
Positive, negative
    L to R
Multiplication, division   L to R
Addition, subtraction     L to R
Relational operator     L to R
Relational operator     L to R
 Logical AND
    L to R
Logical OR
    L to R
Compound assignment   R to L
Assignment
    R to L

1
2
3
3
3
4
5
6
7

8
9
10
10


Example:
Assume:  a = 4, b = ­2, and c = 0
   x = (a > b || b > c && a == b)
x = ((a > b) || (b > c) && (a == b))
x = ((4 > ­2) || (­2 > 0) && (4 == ­2))
Group x = (TRUE || (FALSE && FALSE))
x = (TRUE || FALSE)
x = (TRUE)
x = 1

Group

Lesson 5.5


Example of Single Variable
logical value
– False if value is 0
– True if value is nonzero

if  (c)
    statement1;
else
    statement2;

Lesson 5.5

Statement2 executed if c has 
value of zero, statement1 is 
executed if c has any other 
value but zero.


if­else­if
Shifts program control, step by step, 
through series of statement blocks
Control stops at relational expression 
that tests true

Lesson 5.6


if (relational_expression_1)
            false                
      {
      statement_block_1
      }
else
else if (relational_expression_2)
            false                
      {
      statement_block_2
      }
      .
      .

      .
else
else if (relational_expression_n­1)
              true                  
      {
      statement_block_n­1
      }
else
      {
      statement_block_n
      }
Lesson 5.6

if­else­if Form

This statement block would
be executed!


switch Control Structure
Constructed like if­else­if
Used to transfer control
Can nest switch control structures
Keyword  switch followed by expression
switch (expression)
Must use parentheses
           {
Must result in
            statement block
integer type value

            }
Lesson 5.6


switch Statement Block Syntax
switch (expression)
           {case  constant1:
                   statement1a
                   statement1b
                   …
             case  constant2:
                   statement2a
                   statement2b
                   …
                   …
             default:
                  statements
           }
            
Lesson 5.6








Keyword case only used in 
switch statement

case used to form label
case label is constant 
followed by colon
Constant1, constant2, etc 
must be integer expressions
Constant expressions must 
be unique
default optional, used when 
no match is found


break Statement
switch (expression)
           {case  constant1:
                   statement1a
                   break;                  
             case  constant2:
                   statement2a
                   break;
                   …
             default:
                  statements
           }
            

Terminates execution 
of switch statement
Sends control to point 
of closing brace
Usually last statement 

for each case
If no break, then 
statements in next case 
executed


bool Data Type
Named after mathematician George Boole
Can contain one of only two values (0 or 1)
– true or false, fail or pass, off or on

Declare by using keyword bool
– Example:      bool   salty, hard, acidic;

Assign value
– Example:   acidic = (pH < 7);
Lesson 5.7


bool Variables
Assign keywords true or false 
– good_taste = true

Assign bools to int variables
– int i;  
– i = good_taste

Print bool variables values using cout
– Prints 1 for true or 0 for false
– boolalpha manipulator gives words true or false

Lesson 5.7


Summary
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


×