C++ Engineers and Scientists
C++ Engineers and Scientists
Chapter 4
Selection Structures
Objectives
Selection Criteria
The if-then-else Statement
Nested if Statements
The switch Statement
Applications
Objectives (continued)
Common Programming Errors
A Closer Look at Program Testing
Selection Criteria
if-else statement: implements a decision
structure for two alternatives
Syntax:
if (condition)
statement executed if condition is true;
else
statement executed if condition is false;
10
abs(operandOne operandTwo)<0.000001
11
12
13
14
15
16
17
18
Nested if Statements
if-else statement can contain any valid C++
statement, including another if-else
Nested if statement: an if-else statement
completely contained within another if-else
Use braces to block code, especially when
inner if statement does not have its own
else
19
20
21
General form of an
Figure 4.5b if-else
if-else chain.
statement nested in an
else.
C++ for Engineers and Scientists, Second Edit
22
23
24
25
26
27
28
Summary
Relational expressions, or conditions, are used
to compare operands
If the relation expression is true, its value is 1;
if false, its value is 0
Use logical operators && (AND), || (OR),
and ! (NOT) to construct complex conditions
if-else allows selection between two
alternatives
29
Summary (continued)
An if expression that evaluates to 0 is false; if
non-zero, it is true
if statements can be nested
Chained if statement provides a multiway
selection
Compound statement contains any number of
individual statements enclosed in braces
30
Summary (continued)
switch statement provides a multiway
selection
switch expression is evaluated and compared
to each case value; if a match is found,
execution begins at that cases statements and
continues unless a break is encountered
31