1 Chapter 4 Making Decisions. 2 Topics 4.1 Relational Operators 4.2 The if Statement 4.3 Flags 4.4...

Preview:

Citation preview

1

Chapter 4

Making Decisions

2

Topics

4.1 Relational Operators4.2 The if Statement4.3 Flags4.4 Expanding the if Statement4.5 The if/else Statement4.6 The if/else if Statement4.7 Using a Trailing else4.8 Menus4.9 Nested if Statements

3

Topics

4.10 Logical Operators4.11 Checking Numeric Ranges with Logical Operators4.12 Validating User Input4.13 More About Variable Definitions and Scope4.14 Comparing Strings4.15 The Conditional Operator4.16 The switch Statement4.17 Testing for File Open Errors

4

4.1 Relational Operators

Used to compare numeric values to determine relative order

Relational Operators:

> Greater than< Less than>= Greater than or equal to<= Less than or equal to== Equal to!= Not equal to

5

Relational Expressions

All the relational operators are binary: two operands; All the relational operators have left-to-right associativity: left-to-right order on which an operator works with its operands

Relational expressions are Boolean (i.e., evaluate to true or false)

Examples:12 > 5 is true7 <= 5 is false

if x is 10, then x == 10 is true, x != 8 is true, and x == 8 is false

6

Relational Expressions

Can be assigned to a variable:result = x <= y;

Relational expressions have higher precedence than the assignment operator

Assigns 0 for false, 1 for trueNote: computer will assign 1 to truth,

but 1 is not the only value regarded as true

Do not confuse = and ==

7

Ex.

Assume x is 10, y is 7, and z,a, and b are ints or bools. What’s the outcome of each of following statements

z= x < y; cout << (x > y); a = x >= y; cout << (x <= y); b = y != x;

8

4.2 The if Statement

The if statement can cause statements to execute only under certain conditions

Models the way we mentally evaluate situations: “If it is raining, take an umbrella.”

Format:if (expression)

statement;

9

if statement – what happens

To evaluate:if (expression)

statement; If (expression) is true, then statement

is executed. If (expression) is false, then statement is skipped.

10

if statement – what happens

expression

statement

expressionis true

expressionis false

11

if statement notes

Example: Program 4-2, Do not place ; after (expression) Place statement; on a separate line after

(expression), indented:if (score > 90)

grade = 'A';

12

if statement notes

Don’t test floats, doubles for equalitydouble a=1.5, b=1.5;

a +=0.0000000000001;

if( a==b )

cout<<“Both have the same value”;

else

cout<<“They have different values”; 0 is false; any other value is true

if(value)cout <<“It is true”; Example Program 4-3

13

4.3 Flags

Variable that signals a condition Often implemented as bool As with other variables in functions, must be

assigned an initial value before it is used Example

14

4.4 Expanding the if Statement

To execute > 1 statement as part of an if statement, enclose them in { }:if (score > 90){

grade = 'A';cout << "Good Job!\n";

} { } creates a block of code

15

Ex. Write an if statement that:

Assign 0 to x if y is equal to 20. Assign .20 to commission if sales is greater

than or equal to 10000.00

16

4.5 The if/else Statement

The if/else statement will execute one group of statements if the expression is true, or another group of statements if the expression is false

Allows choice between statements if (expression) is true or false

Format:if (expression)

statement1; // or block

else

statement2; // or block

17

if/else – what happens

To evaluate:if (expression)

statement1;else

statement2; If (expression) is true, then statement1 is

executed and statement2 is skipped. If (expression) is false, then statement1 is

skipped and statement2 is executed.

18

if/else – what happens

expression

statement1

expressionis true

expressionis false

statement2

19

if/else

Example: program 4-6, Ex: write an if/else statement that

assign 1 to x if y is equal to 100. Otherwise it should assign 0 to x

Assign 0.10 to commission unless sales is greater than or equal to 50000.00 in which case it assigns 0.20 to commission

20

4.6 The if/else if Statement

The if/else if statement is a chain of if statements. They perform their tests, one after the other, until one is found to be true

Also models thought processes: “If it is raining, take an umbrella,

else, if it is windy, take a hat, else, take sunglasses”

21

if/else if format

if (expression) statement1; // or block

else if (expression) statement2; // or block . . // other else ifs .

else if (expression) statementn; // or block

Example: prog 4-7, sample input: 70 Prog 4-8, sample input:70

22

4.7 Using a Trailing else

A trailing else, placed at the end of an if/else if statement, provide default action when none of (expression) is true

Provides default statement/action Used to catch invalid values, other

exceptional situations Example: using trailing else

23

4.8 Menus

Use if/else if statements to create menu-driven program

Menu: list of choices on the screen Menu-driven program: program execution

controlled by user selecting from a list of actions

24

Menu-driven program organization

Display list of numbered or lettered choices for actions

Prompt user to make selection Test user selection in (expression)

if a match, then execute code for action if not, then go on to next (expression)

Example: Prog. 4-9

25

4.9 Nested if Statements

A nested if statement is an if statement in the conditionally executed code of another if statement.

Can be used to evaluate > 1 data item or condition:

if (score < 100){

if (score > 90) grade = 'A';

}

26

Notes on coding nested ifs

An else matches the nearest if that does not have an else:if (score < 100)

if (score > 90) grade = 'A'; else ...// goes with second if, // not first one

Proper indentation helps greatly Important: which if statement each else belongs to Example

Ex: write nested if statements that perform the following test: if amount1 is greater than 10 and amout2 is less that 100, display the greater of the two.

27

4.10 Logical Operators

Logical operators connect two or more relational expressions into one or reverse the logic of an expression.

Operators, meaning, and explanation:

&& AND New relational expression is true if both expressions are true

|| OR New relational expression is true if either expression is true

! NOT Reverses the value of an expression – true expression becomes false, and false becomes true

28

Logical Operators - examples

int x = 12, y = 5, z = -4; (x > y) && (y > z)

(x > y) && (z > y)

(x <= z) || (y == z)

(x <= z) || (y != z)

!(x >= z)

29

Logical Operators - precedence

! has highest precedence, followed by &&, then ||a<b || y== z && m> j

! Operator has higher precedence than many of the C++ operators! (x > 2) is not same as !x > 2

&& and || operators rank lower in precedence than the relational operators (a>b) && (x<y) is the same as a> b && x<y

30

Logical Operators - short circuit evaluation If the value of an expression can be

determined by evaluating just the sub-expression on left side of a logical operator, then the sub-expression on the right side will not be evaluated (short circuit evaluation)if ( csGrade > 90 && mathGrade > 90 ) cout<<“Your are very good!”

if ( csGrade > 90 || mathGrade > 90 ) cout<<“Your are very good!”

Example

31

4.11 Checking Numeric Ranges with Logical Operators

Logical operators are effective for determining if a number is in or out of a range

Used to test to see if a value falls into a range:if (grade >= 0 && grade <= 100) cout << "Valid grade";

Can also test to see if value falls outside of range: if (grade < 0 || grade > 100) cout << "Invalid grade";

Cannot use mathematical notation:if (0 <= grade <= 100) //doesn’t work!

Ex: write an if statement that prints the message: “The number is valid” if the variable speed is

within the range 0 through 200 “The number is not valid” if the variable speed

is within outside the range 0 through 200

32

33

4.12 Validating User Input

Input validation: inspecting data to a program to determine if it is acceptable

Bad output will be produced from bad input Can perform various tests:

Range Reasonableness Valid menu choice Divide by zero

Example: Program 4-12

34

4.13 More About Variable Definitions and Scope Scope of a variable is the block in which it is

defined, from the point of definition to the end of the block

Usually defined at beginning of function May be defined close to first use

35

Still More About Variable Definitions and Scope

Variables defined inside { } have local or block scope

When inside a block within another block, can define variables with the same name as in the outer block. When in inner block, outer definition is not available Not a good idea Example

36

4.16 The switch Statement

Used to select among statements from several alternatives

May be used instead of if/else if statements

37

switch statement format

switch (expression) //integer

{

case exp1: statement1;

case exp2: statement2;

...

case expn: statementn;

default: statementn+1;

}

38

switch statement requirements

1) expression must be an integer variable or an expression that evaluates to an integer value

2) exp1 through expn must be constant integer expressions or literals, and must be unique in the switch statement

3) default is optional but recommended

39

switch statement – how it works

1) expression is evaluated

2) The value of expression is compared against exp1 through expn.

3) If expression matches value expi, the program branches to the statement following expi and continues to the end of the switch

4) If no matching value is found, the program branches to the statement after default:

40

break statement

Used to stop execution in the current block Also used to exit a switch statement Useful to execute a single case statement

without executing the statements following it Example:

Prog 4-19 Prog 4-20 Prog 4-21

switch (expression) //integer{

case exp1: statement1;break;

case exp2: statement2;break;

...case expn: statementn;

break;default: statementn+1;

}

41

Using switch with a menu

switch statement is a natural choice for menu-driven program: display menu get user input use user input as expression in switch

statement use menu choices as expr in case

statements Example: Prog 4-22

42

4.17 Testing for File Open Errors

Can test a file stream object to detect if an open operation failed:

infile.open("test.txt");if (!infile){

cout << "File open failure!";}

Can also use the fail member function infile.open("test.txt");

if (infile.fail()){

cout << "File open failure!";}

43

4.14 Comparing Strings

Can not use relational operators with character strings

Must use the strcmp function to compare C-strings

strcmp compares the ASCII codes of the characters in the strings. Comparison is character-by-character

44

Comparing Strings

strcmp(str1, str2): compares strings str1 and str2 (ASCII code)

• returns 0 if the strings are the same, • negative number if str1 < str2, • positive number if str1 > str2

char myName[10] = "George";

char yourName[10] = "Georgia";

if (strcmp(myName,yourName) < 0)

cout << myName << " comes before "

<< yourName << " in the alphabet";

45

Comparing Strings

Example: Prog. 4-16 Prog. 4-17

The two following statements perform the same operationif( strcmp(firstString, secondString) == 0)

if( ! strcmp(firstString, secondString) ) Sorting strings

Example: prog. 4-18

46

4.15 The Conditional Operator

Can use to create short if/else statements Format: expr ? expr : expr; Ternary operator

x<0 ? y=10 : z=20;

First Expression:Expression to betested

2nd Expression:Executes if firstexpression is true

3rd Expression:Executes if the firstexpression is false

a = x > 100 ? 0 : 1; if ( x>100 )a=0;

else a=1;

47

The Conditional Operator

The value of a conditional expression is The value of the second expression if the first

expression is true The value of the third expression if the first

expression is false Parentheses () may be needed in an

expression due to precedence of conditional operatorcout << “Your grade is “

<< (score < 60 ? “Fail.” : “Pass.”);

Recommended