SlideShare a Scribd company logo
1 of 38
Download to read offline
Introduction to Computer Programming
Control Structures – Selection
C++ Programming: From Problem Analysis to Program Design
1
2
Chapter Topics
• Control Structures
• Relational Operators
• Logical (Boolean) Operators
• Logical Expressions
• Selection if ( ) and if ( ) … else
• switch Structures
3
Control Structures
• Statements can be
executed in sequence
• One right after the other
• No deviation from the
specified sequence
4
Control Structures
• A selection
structure can be used
• Which statement
is executed is selected
by whether the
expression
is true or false
5
Control Structures
• Statements can be
repeated
• The number of
repetitions depends
on when the
expression turns
false
6
Relational Operators
• The expressions which determine
– Selection and
– Repetition are usually comparisons
• Comparisons are done with relational operators
Beware of mistaking
the assignment = for
the equality ==
7
Relational Operators
• Examples:
Expression Meaning Value
8 < 15 8 is less than 15 true
6 != 6 6 is not equal to 6 false
2.5 > 5.8 2.5 is greater than 5.8 false
5.9 <= 7.5 5.9 is less than or
equal to 7.5 true
8
Relational Operators
• Given
string str1 = "Hello"; string str2 = "Hi";
string str3 = "Air"; string str4 = "Bill";
string str5 = "Big";
Determine the
values of these
comparisons
using variables
Note: Capital
letters are
smaller than
small letters
Note: A is the
smallest, Z is
the largest
9
Logical (Boolean) Operators
• Logical or Boolean operators enable you to combine
logical expressions
• Operands must be logical values
• The results are logical values (true or false)
A unary operator
Binary operators
10
Logical (Boolean) Operators
• The && operator (logical and)
– If both operands are true, the result is true
– If either or both operands is false, the comparison is false
• The || operator (logical or)
– If either or both of the operands are true, the comparison
is true
– The comparison is false only if both operands are false
• The ! operator (logical not)
– The not operator reverses the logical value of the one
operand
11
Logical Expressions
• We must know the order in which to apply the operators
12 > 7 || 9 * 5 >= 6 && 5 < 9
Highest
Lowest
Order of Precedence
Affects sign of
a number
12
Example
13
Example
14
Example
15
Short Circuit Evaluation
• Consider
(x != 0) && (1.0 / x < 0.25)
• If the first condition is false, the program could crash
when it tried to divide by zero
– but if the first condition is false, the whole expression is false
– no need to go on
• When C++ evaluates an expression, realizes that fact
and does not even make the second comparison
• Called "short circuit" evaluation
If statement Family
1. If
2. If ‐ else
3. Nested If
4. If ‐ else if – else
16
17
Selection if (...)
• C++ has two versions of if statements
• In this version, the condition is checked
– If the expression
is true, the
statement is
executed
– If it is false,
nothing happens
18
Selection if (...)
• Syntax
if ( logicalExpression )
statement;
• Example
if (x < 5)
cout << "low value for x";
Note parentheses
around the condition
Note there is no "then" as
part of the syntax
19
Selection if ( ) … else …
• Also possible to make two way selection
• If the expression is true,
statement1 is executed
• Otherwise statement2
is executed
20
Selection if ( ) … else …
• Syntax
if (condition)
statement1;
else
statement2;
• Example
if (x < 5) cout << "low x";
else cout << "high x";
21
Compound Statements
• Consider the need for multiple statements to be
controlled by the if
• This is called
a compound
statement
• Group the
statements in
curly brackets { }
Statement1;
Statement2;
Statement3;
22
Compound Statements
• Example
if (x < 5)
{
x = x + 10;
cout << x;
}
• Note the use of indenting and white space in the
source code for readability.
The compound
statement
23
Nested if
• Syntax calls for a “statement” after the
if ( … )
• That statement can be any kind of statement
– (List statements we know about)
• It can be an if statement
cout
cin
assignment
if
if (x < 7)
if (y > 5)
cout << “hi mom”;
24
The Dangling else
• How to determine which if the else goes with
• Example:
if (abs (x - 7))
if (x < 7)
cout << “x approaches 7 from left”;
else
cout << “x approaches 7 from the right”;
else
cout << “x not close to 7”;
Rule : An else goes with the closest unmatched if
?
?
25
The Dangling Else
• Rule: an else goes with the closest unmatched if
if (x < y)
if (y > 3)
cout << “message about y > 3”;
else
cout << “message about x and y”;
26
The Dangling Else
• Consider … how do you force an else to go with a
previous if?
if (x < y)
{ if (y > 3)
cout << “message about y > 3”;
}
else
cout << “message about x and y”;
Use { curly brackets }
to nest the statements
27
Multiple Selections
• Consider determining a letter grade based on a score
– Cut off points for A, B, C, and D are 90, 80, 70, and 60
respectively
• We check the score against each of these values
28
Multiple Selections
• Contrast
– A sequence of
if … else if … statements
– A sequence of separate if statements
• What happens in each case when it is the first if
condition that is true?
–if … else if sequence will jump out of the
structure whenever match is found
– sequence of separate if's – each if is checked, no
mater where the match is
29
The if-else if-else Chain: Example 1
30
The if-else Chain: Example 2
31
Multiple Selections
• Recall the current branching capability provided by
the if ( … ) statement
• Only branches two
ways
• We desire a more
eloquent way to do
multiway branching
32
switch Structures
• C++ provides the switch statement
• Best used when you have limited choices not a range
switch (choice)
{
case 1 : do_option_one();
break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b ();
break;
default : do_something_else ();
}
33
switch Structures
• Value of the switch expression matched with one of
the labels attached to a branch
• The statement(s) with the match get executed
switch (choice) {
case 1 : do_option_one(); break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b (); break;
default : do_something_else (); }
34
switch Structures
• Switch expression => the expression in parentheses
whose value determines which switch label is selected
– cannot be floating point
– usually is int or char
• Identifiers
following case
must be constants
switch (choice) {
case 1 : do_option_one(); break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b (); break;
default : do_something_else (); }
35
switch Structures
• The break causes
control to be shifted
to first statement after
the switch statement
• The default
statement is executed
if the value of the
switch expression is
NOT found among
switch labels
switch (choice) {
case 1 : do_option_one();
break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b ();
break;
default : do_something_else ();
}
// next statement
36
The switch Statement: Example 1
37
The switch Statement: Example 2
38
The switch Statement: Example 2

More Related Content

Similar to Selection

Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfComputer Programmer
 
Chaptfffffuuer05.PPT
Chaptfffffuuer05.PPTChaptfffffuuer05.PPT
Chaptfffffuuer05.PPTsdvdsvsdvsvds
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
C++ problem solving operators ( conditional operators,logical operators, swit...
C++ problem solving operators ( conditional operators,logical operators, swit...C++ problem solving operators ( conditional operators,logical operators, swit...
C++ problem solving operators ( conditional operators,logical operators, swit...mshakeel44514451
 
ESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxAvijitChaudhuri3
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptSuleman Khan
 

Similar to Selection (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
CPP04 - Selection
CPP04 - SelectionCPP04 - Selection
CPP04 - Selection
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Control structures i
Control structures i Control structures i
Control structures i
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Using decision statements
Using decision statementsUsing decision statements
Using decision statements
 
Chaptfffffuuer05.PPT
Chaptfffffuuer05.PPTChaptfffffuuer05.PPT
Chaptfffffuuer05.PPT
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
LOOPS AND DECISIONS
LOOPS AND DECISIONSLOOPS AND DECISIONS
LOOPS AND DECISIONS
 
C++ problem solving operators ( conditional operators,logical operators, swit...
C++ problem solving operators ( conditional operators,logical operators, swit...C++ problem solving operators ( conditional operators,logical operators, swit...
C++ problem solving operators ( conditional operators,logical operators, swit...
 
Fekra c++ Course #2
Fekra c++ Course #2Fekra c++ Course #2
Fekra c++ Course #2
 
ESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptx
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 

More from Jason J Pulikkottil

Overview of computers and programming
Overview of computers and programmingOverview of computers and programming
Overview of computers and programmingJason J Pulikkottil
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesJason J Pulikkottil
 
Computer Architecture Performance and Energy
Computer Architecture Performance and EnergyComputer Architecture Performance and Energy
Computer Architecture Performance and EnergyJason J Pulikkottil
 
ARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationJason J Pulikkottil
 
Microprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsMicroprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsJason J Pulikkottil
 
Basic Electronics Theory and Components
Basic Electronics Theory and ComponentsBasic Electronics Theory and Components
Basic Electronics Theory and ComponentsJason J Pulikkottil
 
Deep Learning for Health Informatics
Deep Learning for Health InformaticsDeep Learning for Health Informatics
Deep Learning for Health InformaticsJason J Pulikkottil
 

More from Jason J Pulikkottil (12)

Overview of computers and programming
Overview of computers and programmingOverview of computers and programming
Overview of computers and programming
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Input and Output
Input and OutputInput and Output
Input and Output
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
 
Computer Architecture Performance and Energy
Computer Architecture Performance and EnergyComputer Architecture Performance and Energy
Computer Architecture Performance and Energy
 
ARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture IllustrationARM 7 and 9 Core Architecture Illustration
ARM 7 and 9 Core Architecture Illustration
 
Microprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin ConnectionsMicroprocessors and Microcontrollers 8086 Pin Connections
Microprocessors and Microcontrollers 8086 Pin Connections
 
Basic Electronics Theory and Components
Basic Electronics Theory and ComponentsBasic Electronics Theory and Components
Basic Electronics Theory and Components
 
Electronic Circuits
Electronic CircuitsElectronic Circuits
Electronic Circuits
 
Power Amplifier
Power AmplifierPower Amplifier
Power Amplifier
 
E12 Resistor Series
E12 Resistor SeriesE12 Resistor Series
E12 Resistor Series
 
Deep Learning for Health Informatics
Deep Learning for Health InformaticsDeep Learning for Health Informatics
Deep Learning for Health Informatics
 

Recently uploaded

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 

Selection

  • 1. Introduction to Computer Programming Control Structures – Selection C++ Programming: From Problem Analysis to Program Design 1
  • 2. 2 Chapter Topics • Control Structures • Relational Operators • Logical (Boolean) Operators • Logical Expressions • Selection if ( ) and if ( ) … else • switch Structures
  • 3. 3 Control Structures • Statements can be executed in sequence • One right after the other • No deviation from the specified sequence
  • 4. 4 Control Structures • A selection structure can be used • Which statement is executed is selected by whether the expression is true or false
  • 5. 5 Control Structures • Statements can be repeated • The number of repetitions depends on when the expression turns false
  • 6. 6 Relational Operators • The expressions which determine – Selection and – Repetition are usually comparisons • Comparisons are done with relational operators Beware of mistaking the assignment = for the equality ==
  • 7. 7 Relational Operators • Examples: Expression Meaning Value 8 < 15 8 is less than 15 true 6 != 6 6 is not equal to 6 false 2.5 > 5.8 2.5 is greater than 5.8 false 5.9 <= 7.5 5.9 is less than or equal to 7.5 true
  • 8. 8 Relational Operators • Given string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str5 = "Big"; Determine the values of these comparisons using variables Note: Capital letters are smaller than small letters Note: A is the smallest, Z is the largest
  • 9. 9 Logical (Boolean) Operators • Logical or Boolean operators enable you to combine logical expressions • Operands must be logical values • The results are logical values (true or false) A unary operator Binary operators
  • 10. 10 Logical (Boolean) Operators • The && operator (logical and) – If both operands are true, the result is true – If either or both operands is false, the comparison is false • The || operator (logical or) – If either or both of the operands are true, the comparison is true – The comparison is false only if both operands are false • The ! operator (logical not) – The not operator reverses the logical value of the one operand
  • 11. 11 Logical Expressions • We must know the order in which to apply the operators 12 > 7 || 9 * 5 >= 6 && 5 < 9 Highest Lowest Order of Precedence Affects sign of a number
  • 15. 15 Short Circuit Evaluation • Consider (x != 0) && (1.0 / x < 0.25) • If the first condition is false, the program could crash when it tried to divide by zero – but if the first condition is false, the whole expression is false – no need to go on • When C++ evaluates an expression, realizes that fact and does not even make the second comparison • Called "short circuit" evaluation
  • 16. If statement Family 1. If 2. If ‐ else 3. Nested If 4. If ‐ else if – else 16
  • 17. 17 Selection if (...) • C++ has two versions of if statements • In this version, the condition is checked – If the expression is true, the statement is executed – If it is false, nothing happens
  • 18. 18 Selection if (...) • Syntax if ( logicalExpression ) statement; • Example if (x < 5) cout << "low value for x"; Note parentheses around the condition Note there is no "then" as part of the syntax
  • 19. 19 Selection if ( ) … else … • Also possible to make two way selection • If the expression is true, statement1 is executed • Otherwise statement2 is executed
  • 20. 20 Selection if ( ) … else … • Syntax if (condition) statement1; else statement2; • Example if (x < 5) cout << "low x"; else cout << "high x";
  • 21. 21 Compound Statements • Consider the need for multiple statements to be controlled by the if • This is called a compound statement • Group the statements in curly brackets { } Statement1; Statement2; Statement3;
  • 22. 22 Compound Statements • Example if (x < 5) { x = x + 10; cout << x; } • Note the use of indenting and white space in the source code for readability. The compound statement
  • 23. 23 Nested if • Syntax calls for a “statement” after the if ( … ) • That statement can be any kind of statement – (List statements we know about) • It can be an if statement cout cin assignment if if (x < 7) if (y > 5) cout << “hi mom”;
  • 24. 24 The Dangling else • How to determine which if the else goes with • Example: if (abs (x - 7)) if (x < 7) cout << “x approaches 7 from left”; else cout << “x approaches 7 from the right”; else cout << “x not close to 7”; Rule : An else goes with the closest unmatched if ? ?
  • 25. 25 The Dangling Else • Rule: an else goes with the closest unmatched if if (x < y) if (y > 3) cout << “message about y > 3”; else cout << “message about x and y”;
  • 26. 26 The Dangling Else • Consider … how do you force an else to go with a previous if? if (x < y) { if (y > 3) cout << “message about y > 3”; } else cout << “message about x and y”; Use { curly brackets } to nest the statements
  • 27. 27 Multiple Selections • Consider determining a letter grade based on a score – Cut off points for A, B, C, and D are 90, 80, 70, and 60 respectively • We check the score against each of these values
  • 28. 28 Multiple Selections • Contrast – A sequence of if … else if … statements – A sequence of separate if statements • What happens in each case when it is the first if condition that is true? –if … else if sequence will jump out of the structure whenever match is found – sequence of separate if's – each if is checked, no mater where the match is
  • 29. 29 The if-else if-else Chain: Example 1
  • 31. 31 Multiple Selections • Recall the current branching capability provided by the if ( … ) statement • Only branches two ways • We desire a more eloquent way to do multiway branching
  • 32. 32 switch Structures • C++ provides the switch statement • Best used when you have limited choices not a range switch (choice) { case 1 : do_option_one(); break; case 2 : case 3 : do_2_3_a (); do_2_3_b (); break; default : do_something_else (); }
  • 33. 33 switch Structures • Value of the switch expression matched with one of the labels attached to a branch • The statement(s) with the match get executed switch (choice) { case 1 : do_option_one(); break; case 2 : case 3 : do_2_3_a (); do_2_3_b (); break; default : do_something_else (); }
  • 34. 34 switch Structures • Switch expression => the expression in parentheses whose value determines which switch label is selected – cannot be floating point – usually is int or char • Identifiers following case must be constants switch (choice) { case 1 : do_option_one(); break; case 2 : case 3 : do_2_3_a (); do_2_3_b (); break; default : do_something_else (); }
  • 35. 35 switch Structures • The break causes control to be shifted to first statement after the switch statement • The default statement is executed if the value of the switch expression is NOT found among switch labels switch (choice) { case 1 : do_option_one(); break; case 2 : case 3 : do_2_3_a (); do_2_3_b (); break; default : do_something_else (); } // next statement