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
 
IF & SWITCH (conditional control) in computer science
IF & SWITCH (conditional control) in computer scienceIF & SWITCH (conditional control) in computer science
IF & SWITCH (conditional control) in computer scienceRaianaTabitha
 
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
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleumaghosal12101974
 
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
 

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
 
IF & SWITCH (conditional control) in computer science
IF & SWITCH (conditional control) in computer scienceIF & SWITCH (conditional control) in computer science
IF & SWITCH (conditional control) in computer science
 
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
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment example
 
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
 

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

💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...jabtakhaidam7
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 

Recently uploaded (20)

💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 

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