SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Transaction states and properties
Transaction states and propertiesTransaction states and properties
Transaction states and propertiesChetan Mahawar
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design) Tasif Tanzim
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationBadrul Alam
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c languagesneha2494
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming LanguageExplore Skilled
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generationAkshaya Arunan
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Looping statement in vb.net
Looping statement in vb.netLooping statement in vb.net
Looping statement in vb.netilakkiya
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C pptMANJUTRIPATHI7
 
Looping statement
Looping statementLooping statement
Looping statementilakkiya
 
Operators in Python
Operators in PythonOperators in Python
Operators in PythonAnusuya123
 

Was ist angesagt? (20)

Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Transaction states and properties
Transaction states and propertiesTransaction states and properties
Transaction states and properties
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 
Switch case in C++
Switch case in C++Switch case in C++
Switch case in C++
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition Presentation
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
php
phpphp
php
 
Looping statement in vb.net
Looping statement in vb.netLooping statement in vb.net
Looping statement in vb.net
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 
Looping statement
Looping statementLooping statement
Looping statement
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 

Andere mochten auch

Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for BloggersAhmad Idrees
 
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 CDDavid Ware
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer VisionBrian Thorne
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessmanAhmad Idrees
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
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 GSEDominic Storey
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of businessAhmad Idrees
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing Ahmad Idrees
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing Ahmad Idrees
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer SystemAhmad Idrees
 
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
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement Ahmad Idrees
 

Andere mochten auch (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
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
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
 

Ähnlich wie Control structures in C++ Programming Language

Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
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 Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
CSC111-Chap_03.pdf
CSC111-Chap_03.pdfCSC111-Chap_03.pdf
CSC111-Chap_03.pdf2b75fd3051
 
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++ Neeru Mittal
 
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
 
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
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection StatementsSzeChingChen
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 

Ähnlich wie 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
 
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
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 

Mehr von Ahmad Idrees

Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer Ahmad Idrees
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's Ahmad Idrees
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information Ahmad Idrees
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle Ahmad Idrees
 
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 Ahmad Idrees
 
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 aboutAhmad Idrees
 

Mehr von 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
 

Kürzlich hochgeladen

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Kürzlich hochgeladen (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

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