You are on page 1of 27

10/25/2018

Chapter 4: Making Decisions Topics


4.1 Relational Operators
Starting Out with C++ 4.2 The if Statement
Early Objects
Eighth Edition 4.3 The if/else Statement
4.4 The if/else if Statement
by Tony Gaddis, Judy Walters,
and Godfrey Muganda 4.5 Menu-Driven Programs
4.6 Nested if Statements
4.7 Logical Operators

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-2

1
10/25/2018

4.1 Relational Operators


Topics (continued)
4.8 Validating User Input • Used to compare numeric values to
4.9 More About Block and Scope determine relative order
4.10 More About Characters and Strings • Operators:
4.11 The Conditional Operator
> Greater than
4.12 The switch Statement < Less than
4.13 Enumerated Data Types >= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-3 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-4

2
10/25/2018

Relational Expressions Relational Expressions

• Relational expressions are Boolean • Can be assigned to a variable


(i.e., evaluate to true or false) bool result = (x <= y);
• Examples:
12 > 5 is true • Assigns 0 for false, 1 for true
7 <= 5 is false • Do not confuse = (assignment) and ==
if x is 10, then (equal to)
x == 10 is true,
x <= 8 is false,
x != 8 is true, and
x == 8 is false
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-5 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-6

3
10/25/2018

4.2 The if Statement


Format of the if Statement
• Supports the use of a decision structure No
if (condition) ; goes here
• Allows statements to be conditionally {
executed or skipped over statement1;
• Models the way we mentally evaluate statement2; ; goes here
situations …
statementn;
“If it is cold outside, }
wear a coat and wear a hat.”
The block inside the braces is called the body
of the if statement. If there is only 1 statement
in the body, the { } may be omitted.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-7 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-8

4
10/25/2018

How the if Statement Works if Statement Flow of Control

• If (condition) is true, then the


statement(s) in the body are executed.
condition
• If (condition) is false, then the
statement(s) are skipped. true false
1 or more
statements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-9 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-10

5
10/25/2018

Example if Statements if Statement Notes

if (score >= 60) • if is a keyword. It must be lowercase


cout << "You passed." << endl;
• (condition)must be in ( )
if (score >= 90) • Do not place ; after (condition)
{
grade = 'A'; • Don't forget the { } around a multi-statement
cout << "Wonderful job!" << endl; body
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-11 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-12

6
10/25/2018

if Statement Style Recommendations What is true and false?

• Place each statement; on a separate • An expression whose value is 0 is


line after (condition) considered false.
• Indent each statement in the body • An expression whose value is non-zero is
considered true.
• When using { and } around the body, put { • An expression need not be a comparison –
and } on lines by themselves it can be a single variable or a
mathematical expression.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-13 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-14

7
10/25/2018

Flag Flag Example


• A variable that signals a condition Example:
bool validMonths = true;
• Usually implemented as a bool

• Meaning: if (months < 0)
– true: the condition exists validMonths = false;
– false: the condition does not exist …
if (validMonths)
• The flag value can be both set and tested moPayment = total / months;
with if statements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-15 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-16

8
10/25/2018

4.3 The if/else Statement


Integer Flags
• Integer variables can be used as flags • Allows a choice between statements
depending on whether (condition) is true
• Remember that 0 means false, any other or false
value means true • Format: if (condition)
int allDone = 0; // set to false {
… statement set 1;
if (count > MAX_STUDENTS) }
allDone = 1; // set to true else
… {
if (allDone) statement set 2;
cout << "Task finished"; }
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-17 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-18

9
10/25/2018

How the if/else Works if/else Flow of Control

• If (condition) is true, statement


set 1 is executed and statement set 2 true condition
false
is skipped.

• If (condition) is false, statement statement statement


set 1 is skipped and statement set 2 set 1 set 2

is executed.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-19 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-20

10
10/25/2018

Example if/else Statements Comparisons with floating-point numbers

if (score >= 60)


• It is difficult to test for equality when
cout << "You passed.\n";
else working with floating point numbers.
cout << "You did not pass.\n";
• It is better to use
if (intRate > 0) – greater than, less than tests, or
{ interest = loanAmt * intRate; – test to see if value is very close to a given
cout << interest; value
}
else
cout << "You owe no interest.\n";
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-21 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-22

11
10/25/2018

if/else if Format
4.4 The if/else if Statement
if (condition 1)
{ statement set 1;
• Chain of if statements that test in order }
until one is found to be true else if (condition 2)
• Also models thought processes { statement set 2;
}
“If it is raining, take an umbrella,

else, if it is windy, take a hat,
else if (condition n)
else, if it is sunny, take sunglasses.”
{ statement set n;
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-23 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-24

12
10/25/2018

Using a Trailing else Example if/else if with Trailing else


if (age >= 21)
• Used with if/else if statement when all
cout << "Adult";
of the conditions are false
else if (age >= 13)
• Provides a default statement or action that cout << "Teen";
is performed when none of the conditions is
else if (age >= 2)
true
cout << "Child";
• Can be used to catch invalid values or else
handle other exceptional situations cout << "Baby";

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-25 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-26

13
10/25/2018

4.5 Menu-Driven Program Menu-driven Program Organization

• Menu: list of choices presented to the user • Display list of numbered or lettered choices
on the computer screen for actions.
• Menu-driven program: program execution • Input user’s selection of number or letter
controlled by user selecting from a list of
• Test user selection in (condition)
actions
– if a match, then execute code to carry out
• Menu can be implemented using desired action
if/else if statements
– if not, then test with next (condition)

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-27 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-28

14
10/25/2018

4.6 Nested if Statements Notes on Coding Nested ifs


• An if statement that is part of the if or
else part of another if statement • An else matches the nearest previous if
that does not have an else
• Can be used to evaluate > 1 data item or
condition if (score < 100)
if (score > 90)
if (score < 100)
grade = 'A';
{
else ... // goes with second if,
if (score > 90)
// not first one
grade = 'A';
} • Proper indentation aids comprehension
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-29 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-30

15
10/25/2018

4.7 Logical Operators Logical Operator Examples

Used to create relational expressions from int x = 12, y = 5, z = -4;


other relational expressions •
(x > y) && (y > z) true
Operator Meaning Explanation
(x > y) && (z > y) false
New relational expression is true if both
&& AND expressions are true
(x <= z) || (y == z) false
New relational expression is true if either
|| OR expression is true
(x <= z) || (y != z) true
Reverses the value of an expression; true
! NOT expression becomes false, false
!(x >= z) false
expression becomes true

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-31 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-32

16
10/25/2018

Logical Precedence More on Precedence

Highest ! Highest arithmetic operators


&& relational operators
Lowest || Lowest logical operators

Example: Example:
(2 < 3) || (5 > 6) && (7 > 8) 8 < 2 + 7 || 5 == 6 is true

is true because AND is evaluated before OR

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-33 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-34

17
10/25/2018

Checking Numeric Ranges with 4.8 Validating User Input


Logical Operators
• Input validation: inspecting input data to
• Used to test if a value is within a range determine if it is acceptable
if (grade >= 0 && grade <= 100)
cout << "Valid grade"; • Want to avoid accepting bad input
• Can also test if a value lies outside a range • Can perform various tests
if (grade <= 0 || grade >= 100) – Range
cout << "Invalid grade"; – Reasonableness
• Cannot use mathematical notation
– Valid menu choice
if (0 <= grade <= 100) //Doesn’t
//work! – Zero as a divisor

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-35 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-36

18
10/25/2018

4.9 More About Blocks and Scope More About Blocks and Scope

• Scope of a variable is the block in which it


• Variables defined inside { } have local or
is defined, from the point of definition to the
block scope
end of the block
• Variables are usually defined at the • When in a block that is nested inside
another block, you can define variables
beginning of a function
with the same name as in the outer block.
• They may instead be defined close to the – When the program is executing in the inner
place where they are first used block, the outer definition is not available
– This is generally not a good idea
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-37 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-38

19
10/25/2018

4.10 More About Characters and Strings Testing Characters


• Can use relational operators with characters and require cctype header file
string objects
if (menuChoice == 'A')
if (firstName == "Beth") FUNCTION MEANING
• Comparing characters is really comparing ASCII isalpha true if arg. is a letter, false otherwise
values of characters isalnum true if arg. is a letter or digit, false
• Comparing string objects is comparing the ASCII otherwise
values of the characters in the strings. Comparison isdigit true if arg. is a digit 0-9, false otherwise
is character-by-character islower true if arg. is lowercase letter, false
• Cannot compare C-style strings with relational otherwise
operators
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-39 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-40

20
10/25/2018

Character Testing 4.11 The Conditional Operator


require cctype header file • Can use to create short if/else
statements
FUNCTION MEANING
isprint true if arg. is a printable character, false
• Format: expr ? expr : expr;
otherwise
ispunct true if arg. is a punctuation character,
false otherwise
isupper true if arg. is an uppercase letter, false
otherwise
isspace true if arg. is a whitespace character, false
otherwise

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-41 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-42

21
10/25/2018

4.12 The switch Statement switch Statement Format


switch (IntExpression)
• Used to select among statements from
{
several alternatives
case exp1: statement set 1;
case exp2: statement set 2;
• May sometimes be used instead of
...
if/else if statements
case expn: statement set n;
default: statement set n+1;
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-43 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-44

22
10/25/2018

switch Statement Requirements


How the switch Statement Works
1) IntExpression must be a char or an 1) IntExpression is evaluated
integer variable or an expression that 2) The value of intExpression is compared
evaluates to an integer value against exp1 through expn.

2) exp1 through expn must be constant 3) If IntExpression matches value expi, the
program branches to the statement(s) following
integer type expressions and must be expi and continues to the end of the switch
unique in the switch statement 4) If no matching value is found, the program
3) default is optional but recommended branches to the statement after default:

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-45 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-46

23
10/25/2018

The break Statement Example switch Statement

• Used to stop execution in the current block switch (gender)


{
• Also used to exit a switch statement case 'f': cout << "female";
break;
• Useful to execute a single case statement case 'm': cout << "male";
without executing statements following it break;
default : cout << "invalid gender";
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-47 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-48

24
10/25/2018

Using switch with a Menu 4.13 Enumerated Data Types


switch statement is a natural choice for
menu-driven program • Data type created by programmer
– display menu • Contains a set of named constant integers
– get user input • Format:
– use user input as IntExpression in switch enum name {val1, val2, … valn};
statement
– use menu choices as exp to test against in the • Examples:
case statements enum Fruit {apple, grape, orange};
enum Days {Mon, Tue, Wed, Thur, Fri};

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-49 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-50

25
10/25/2018

Enumerated Data Type Variables Enumerated Data Type Values


• To define variables, use the enumerated • Enumerated data type values are
data type name associated with integers, starting at 0
Fruit snack; enum Fruit {apple, grape, orange};
Days workDay, vacationDay;
0 1 2
• Variable may contain any valid value for the
data type • Can override default association
snack = orange; // no quotes enum Fruit {apple = 2, grape = 4,
orange = 5}
if (workDay == Wed) // none here
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-51 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-52

26
10/25/2018

Enumerated Data Type Notes Chapter 4: Making Decisions

• Enumerated data types improve the Starting Out with C++


Early Objects
readability of a program Eighth Edition
• Enumerated variables can not be used with
by Tony Gaddis, Judy Walters,
input statements, such as cin and Godfrey Muganda
• Will not display the name associated with
the value of an enumerated data type if
used with cout

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-53 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

27

You might also like