SlideShare uma empresa Scribd logo
1 de 34
Control Structures – Selection
Ahmad Idrees
2
Chapter Topics
 Control Structures
 Relational Operators
 Logical (Boolean) Operators
 Logical Expressions
 Selection if ( ) and
if ( ) … else
 switch Structures
 The assert Function
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
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
View
Sample
Program
12
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
13
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
14
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
15
Selection if ( ) … else …
 Also possible to make two way selection
 If the expression is
true, statement1 is
executed
 Otherwise statement2
is executed
16
Selection if ( ) … else …
 Syntax
if (condition)
statement1;
else
statement2;
 Example
if (x < 5) cout << "low x";
else cout << "high x";
View sample
program
17
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;
18
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
19
The Nested if
IF
20
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”;
21
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
?
?
22
The Dangling Else
 Rule : an else goes with the closest
unmatched if
 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”;
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
23
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
 See source code
24
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
25
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
26
switch Structures
 C++ provides the switch statement
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 (); }
27
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 (); }
28
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 (); }
29
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
30
Testing the State of an I/O Stream
 The name of the input stream (used by
itself) returns a value
• returns a 0 if it is NOT successful
• it returns a NON zero value if it IS
successful
31
Testing the State of an I/O Stream
 When reading a file (a named input
stream) we wish to know when it
reaches the end
 Since the name returns a 0 or non-0, this
can be used as a Boolean value
 Used to control program sequencing,
control a file reading loop
32
The assert Function
 Some statements will compile and run
fine in normal situations
 Certain values may cause a statement to
crash the program
• What might happen in this statement?
root = -b + sqrt(b * b – 4 * a * c);
The program will crash if it tries to take the
square root of a negative number
33
The assert Function
 C++ provides a function which can check
specified conditions
• If the condition is true the program continues
• If the condition is false, it will cleanly terminate the
program
• It displays a message as to what condition caused
the termination
 Syntax
assert ( logicalValue);
 Note, you must #include <assert>
34
The assert Function
 Example:
assert (b * b - 4 * a * c >= 0);
root = -b + sqrt(b * b – 4 * a * c);
 At run time the assertion condition is checked
• If true program continues
• If false, the assert halts the program
 Good for debugging stage of your program
• Shows you places where you have not written the
code to keep things from happening
• Once fully tested, asserts might be commented
out

Mais conteúdo relacionado

Mais procurados

Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in Java
Jin Castor
 

Mais procurados (20)

Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Linked list
Linked listLinked list
Linked list
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Control statements
Control statementsControl statements
Control statements
 
Function
FunctionFunction
Function
 
Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in Java
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Loops c++
Loops c++Loops c++
Loops c++
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Function in C
Function in CFunction in C
Function in C
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 

Destaque

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
Ahmad Idrees
 

Destaque (20)

Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSE
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
What is business
What is businessWhat is business
What is business
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 

Semelhante a Control structures in C++ Programming Language

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 

Semelhante a Control structures in C++ Programming Language (20)

Selection
SelectionSelection
Selection
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Ch05-converted.pptx
Ch05-converted.pptxCh05-converted.pptx
Ch05-converted.pptx
 
Control structures i
Control structures i Control structures i
Control structures i
 
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 Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
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
 
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
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 

Mais de Ahmad Idrees

Mais de Ahmad Idrees (6)

Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know about
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Último (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Control structures in C++ Programming Language

  • 1. Control Structures – Selection Ahmad Idrees
  • 2. 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions  Selection if ( ) and if ( ) … else  switch Structures  The assert Function
  • 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
  • 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 View Sample Program
  • 12. 12 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
  • 13. 13 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
  • 14. 14 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
  • 15. 15 Selection if ( ) … else …  Also possible to make two way selection  If the expression is true, statement1 is executed  Otherwise statement2 is executed
  • 16. 16 Selection if ( ) … else …  Syntax if (condition) statement1; else statement2;  Example if (x < 5) cout << "low x"; else cout << "high x"; View sample program
  • 17. 17 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;
  • 18. 18 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
  • 20. 20 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”;
  • 21. 21 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 ? ?
  • 22. 22 The Dangling Else  Rule : an else goes with the closest unmatched if  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”; 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
  • 23. 23 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  See source code
  • 24. 24 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
  • 25. 25 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
  • 26. 26 switch Structures  C++ provides the switch statement 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 (); }
  • 27. 27 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 (); }
  • 28. 28 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 (); }
  • 29. 29 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
  • 30. 30 Testing the State of an I/O Stream  The name of the input stream (used by itself) returns a value • returns a 0 if it is NOT successful • it returns a NON zero value if it IS successful
  • 31. 31 Testing the State of an I/O Stream  When reading a file (a named input stream) we wish to know when it reaches the end  Since the name returns a 0 or non-0, this can be used as a Boolean value  Used to control program sequencing, control a file reading loop
  • 32. 32 The assert Function  Some statements will compile and run fine in normal situations  Certain values may cause a statement to crash the program • What might happen in this statement? root = -b + sqrt(b * b – 4 * a * c); The program will crash if it tries to take the square root of a negative number
  • 33. 33 The assert Function  C++ provides a function which can check specified conditions • If the condition is true the program continues • If the condition is false, it will cleanly terminate the program • It displays a message as to what condition caused the termination  Syntax assert ( logicalValue);  Note, you must #include <assert>
  • 34. 34 The assert Function  Example: assert (b * b - 4 * a * c >= 0); root = -b + sqrt(b * b – 4 * a * c);  At run time the assertion condition is checked • If true program continues • If false, the assert halts the program  Good for debugging stage of your program • Shows you places where you have not written the code to keep things from happening • Once fully tested, asserts might be commented out