0% found this document useful (0 votes)
40 views42 pages

Selection Structure

This chapter discusses selection structures in C++, which allow a program to make decisions by selecting different code paths based on conditional logic. The chapter covers: - Using if/else statements to implement single and dual-alternative selection structures - Comparison operators like <, >, == that are used in conditional expressions - Logical operators like && and || that combine multiple conditions It provides examples of programs that swap values, calculate sums/differences, validate input, and check for pass/fail conditions using selection structures. Flowcharts and truth tables are used to illustrate the control flow and logical evaluation.

Uploaded by

LawrOot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views42 pages

Selection Structure

This chapter discusses selection structures in C++, which allow a program to make decisions by selecting different code paths based on conditional logic. The chapter covers: - Using if/else statements to implement single and dual-alternative selection structures - Comparison operators like <, >, == that are used in conditional expressions - Logical operators like && and || that combine multiple conditions It provides examples of programs that swap values, calculate sums/differences, validate input, and check for pass/fail conditions using selection structures. Flowcharts and truth tables are used to illustrate the control flow and logical evaluation.

Uploaded by

LawrOot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to Programming in C++

Seventh Edition

Chapter 5:
The Selection Structure
Objectives

• Include the selection structure in pseudocode and in a


flowchart
• Code a selection structure using the if statement
• Include comparison operators in a selection structure’s
condition
• Include logical operators in a selection structure’s
condition
• Format numeric output

An Introduction to Programming with C++, Seventh Edition 2


Making Decisions

• With only the sequence structure, all instructions are


executed in order
• A selection structure is needed when a decision must
be made (based on some condition) before selecting an
instruction to execute
• A selection structure’s condition must be phrased as a
Boolean expression (evaluates to true or false)

An Introduction to Programming with C++, Seventh Edition 3


Making Decisions (cont’d.)

• Single-alternative selection structure


– Set of instructions is executed only if condition evaluates to
true
• Dual-alternative selection structure
– Executes different sets of instructions based on whether
condition evaluates to true or false
• True path
– Instructions followed when condition evaluates to true
• False path
– Instructions followed when condition evaluates to false

An Introduction to Programming with C++, Seventh Edition 4


Coding a Selection Structure in C++

• The if (and else) statement is used to code most


selection structures in C++
• Syntax
if (condition)
one or more statements (true path)
[else
one or more statements (false path)]
• Keyword if and condition are required
• Portion in brackets (else clause) is optional
– Only used for dual-alternative selection structures

An Introduction to Programming with C++, Seventh Edition 5


Coding a Selection Structure in C++
(cont’d.)
• Programmer must supply condition and statements in
true (and, optionally, false) path
• If path contains more than one statement, must be
entered as a statement block (enclosed in {})
• Good programming practice to put comment at end of
clause (example: //end if)
– Makes program easier to read and understand
• The condition must be a Boolean expression
– May contain variables, constants, arithmetic operators,
comparison operators, and logical operators

An Introduction to Programming with C++, Seventh Edition 6


Coding a Selection Structure in C++
(cont’d.)

Figure 5-6 How to use the if statement

An Introduction to Programming with C++, Seventh Edition 7


Figure 5-6 How to use the if statement (cont’d)

An Introduction to Programming with C++, Seventh Edition 8


Comparison Operators

• Comparison operators are used to compare two values


that have the same data type
– less than (<)
– less than or equal to (<=)
– greater than (>)
– greater than or equal to (>=)
– equal to (==)
– not equal to (!=)
• No spaces between dual-character symbols

An Introduction to Programming with C++, Seventh Edition 9


Comparison Operators (cont’d.)

• Have precedence numbers like arithmetic operators


• <, <=, >, and >= have precedence value 1
• == and != have precedence value 2
• Lower precedence evaluated first
• Equal precedence evaluated left to right
• Parentheses used to override precedence order

An Introduction to Programming with C++, Seventh Edition 10


Comparison Operators (cont’d.)

• Expressions with comparison operators always evaluate


to Boolean values
• Don’t confuse equality operator (==) with assignment
operator (=)
• Don’t use equality (==) or inequality operator (!=) to
compare real numbers
– Real numbers cannot be stored exactly
– Instead, test that absolute value of their difference is
within some small threshold

An Introduction to Programming with C++, Seventh Edition 11


Comparison Operators (cont’d.)

Figure 5-7 How to use comparison operators


in an if statement’s condition
An Introduction to Programming with C++, Seventh Edition 12
Comparison Operators (cont’d.)

Figure 5-8 Evaluation steps for an expression containing


arithmetic and comparison operators

An Introduction to Programming with C++, Seventh Edition 13


Swapping Numeric Values

• Example program (next slide) takes in two integers,


swaps them if first is greater, and then prints out lower
number, followed by higher number
• Uses single-alternative selection structure with
statement block in true path
• Creates temporary variable to accomplish swap
• Temp variable can only be used in statement block in
which it is declared; called a local variable

An Introduction to Programming with C++, Seventh Edition 14


Swapping Numeric Values (cont’d.)

Figure 5-9 IPO chart information and C++


instructions for the swapping program
An Introduction to Programming with C++, Seventh Edition 15
Swapping Numeric Values (cont’d.)

Figure 5-10 Illustration of the swapping concept

An Introduction to Programming with C++, Seventh Edition 16


Displaying the Sum or Difference

• Example program (next slide) displays the sum or


difference of two numbers entered by the user
• Choice of addition or subtraction is entered by user as
well
• Uses a dual-alternative selection structure

An Introduction to Programming with C++, Seventh Edition 17


Displaying the Sum or Difference
(cont’d.)

Figure 5-13 IPO chart information and C++


instructions for the sum or difference program

An Introduction to Programming with C++, Seventh Edition 18


Logical Operators

• Logical operators allow you to combine two or more


conditions (sub-conditions) into one compound
condition
• Also called as Boolean operators (always evaluate to
true or false)
• Two most common are And (&&) and Or (||)
• All sub-conditions must be true for a compound
condition using And to be true
• Only one of the sub-conditions must be true for a
compound condition using Or to be true
An Introduction to Programming with C++, Seventh Edition 19
Logical Operators (cont’d.)

• And evaluated before Or in an expression


• Logical operators evaluated after arithmetic and
comparison operators
• Parentheses can override precedence ordering
• Truth tables summarize how computer evaluates logical
operators
• Only necessary sub-conditions are evaluated; called
short-circuit evaluation
– Example: if first sub-condition in an And clause is false,
second sub-condition need not be evaluated
An Introduction to Programming with C++, Seventh Edition 20
Logical Operators (cont’d.)

Figure 5-16 How to use logical operators in an if statement’s condition

An Introduction to Programming with C++, Seventh Edition 21


Logical Operators (cont’d.)

Figure 5-16 How to use logical operators in


an if statement’s condition (cont’d)
An Introduction to Programming with C++, Seventh Edition 22
Logical Operators (cont’d.)

Figure 5-17 Truth tables for the logical operators

An Introduction to Programming with C++, Seventh Edition 23


Using the Truth Tables

• Two example problem descriptions are given, and truth


tables for And and Or operators are used to find
appropriate sub-conditions and logical operators
• Calculate bonus for A-rated salespeople with monthly
sales greater than $5000
rating == ‘A’ && sales > 5000
• Send letter to all A-rated and B-rated salespeople
rating == ‘A’ || rating == ‘B’

An Introduction to Programming with C++, Seventh Edition 24


Calculating Gross Pay

• Example problem description is given in which the gross


pay of an employee must be calculated
• Program must verify that number of hours worked is
between 0 and 40
• Process of verifying that input data is within expected
range is known as data validation
• Program outputs gross pay if the number of hours
worked is valid and is an error message otherwise

An Introduction to Programming with C++, Seventh Edition 25


Calculating Gross Pay (cont’d.)

An Introduction to Programming with C++, Seventh Edition 26


Calculating Gross Pay (cont’d.)

Figure 5-19 First sample run of


the gross pay program’s code

Figure 5-20 Second sample run of


the gross pay program’s code

An Introduction to Programming with C++, Seventh Edition 27


Pass/Fail Program

• Example problem description is given in which program


must output “Pass” if user enters ‘P’ or ‘p’, and “Fail”
otherwise
• Character comparisons are case sensitive in C++
• Program must check separately whether the user
entered ‘P’ or ‘p’
• Dual-alternative selection structure is used to
implement program
• Compound condition with Or operator is used to
perform check
An Introduction to Programming with C++, Seventh Edition 28
Pass/Fail Program (cont’d)

An Introduction to Programming with C++, Seventh Edition 29


Pass/Fail Program (cont’d.)

Figure 5-22 First sample run of


the Pass/Fail program’s code

Figure 5-23 Second sample run of


the Pass/Fail program’s code

An Introduction to Programming with C++, Seventh Edition 30


Summary of Operators

Figure 5-24 Listing and an example of


arithmetic, comparison, and logical operators
An Introduction to Programming with C++, Seventh Edition 31
Converting a Character to Uppercase
or Lowercase
• toupper and tolower functions used to convert
characters between uppercase and lowercase
• toupper function temporarily converts a character to
uppercase; tolower function temporarily converts a
character to lowercase
• Syntax is toupper(charVariable) and
tolower(charVariable)
• Item between parentheses in a function’s syntax is
called an argument – information the function needs to
perform its task

An Introduction to Programming with C++, Seventh Edition 32


Converting a Character to Uppercase
or Lowercase (cont’d.)
• Each function copies the character in its argument to a
temporary location in internal memory, converts the
character to the appropriate case, and returns the
temporary character
• Neither function changes the contents of its argument,
but rather, changes the temporary variable

An Introduction to Programming with C++, Seventh Edition 33


Converting a Character to Uppercase
or Lowercase (cont’d.)

Figure 5-25 How to use the toupper and tolower functions


An Introduction to Programming with C++, Seventh Edition 34
Formatting Numeric Output

• Real numbers are displayed in either fixed-point or


scientific (e) notation
• Small real numbers (six or less digits before decimal
place) displayed in fixed-point notation
– Example: 1,234.56 displayed as 1234.560000
• Large real numbers (more than six digits before decimal
place) displayed in e notation
– Example: 1,225,000.00 displayed as 1.225e+006
• Purpose of program determines appropriate format

An Introduction to Programming with C++, Seventh Edition 35


Formatting Numeric Output (cont’d.)

• Stream manipulators allow control over formatting


• fixed stream manipulator displays real numbers in
fixed-point notation
• scientific stream manipulator displays real
numbers in e notation
• Stream manipulator must appear in a cout statement
before numbers you want formatted
• Manipulator can appear by itself in a cout statement or
can be included with other information

An Introduction to Programming with C++, Seventh Edition 36


Formatting Numeric Output (cont’d.)

• Manipulator remains in effect until end of program


execution or until another manipulator is processed
• Numbers formatted with fixed stream manipulator
always have six numbers to the right of the decimal
place
– Number is padded with zeros if there aren’t six digits
• Example: 123.456 is displayed as 123.456000
– Number is rounded and truncated if there are more than
six digits
• Example: 123.3456789 is displayed as 123.345679

An Introduction to Programming with C++, Seventh Edition 37


Formatting Numeric Output (cont’d.)

• setprecision stream manipulator controls number


of decimal places
• Syntax setprecision(numberOfDecimalPlaces)
• You can include setprecision and fixed
manipulators in the same cout statement
• Definition of setprecision manipulator contained in
iomanip file
• Program must contain #include <iomanip>
directive to use setprecision manipulator

An Introduction to Programming with C++, Seventh Edition 38


Formatting Numeric Output (cont’d.)

Figure 5-26 How to use the fixed


and scientific stream manipulators
An Introduction to Programming with C++, Seventh Edition 39
Formatting Numeric Output (cont’d.)

Figure 5-27 How to use the


setprecision stream manipulator

An Introduction to Programming with C++, Seventh Edition 40


Problem

• Create a program that will determine the equivalent


grade. Grade Equivalent Grade
0 Failed
60 3.0
65 2.75
70 2.50
75 2.25
80 2.0
85 1.75
90 1.50
95 1.25
97 1.0

An Introduction to Programming with C++, Seventh Edition 41


Sample

Enter Grade = 50
Equivalent Grade = FAILED

Enter Grade = 65.5


Equivalent Grade = 2.75

An Introduction to Programming with C++, Seventh Edition 42

You might also like