SlideShare a Scribd company logo
An Introduction To Software
Development Using C++
Class #9:
Control Statements:
Part 1
Next Steps
•Our next step is to present the theory and principles of
structured programming.
•
•The concepts presented here are crucial to building
effective classes and manipulating objects.
•
•We introduce C++’s if, if…else and while statements,
three of the building blocks that allow you to specify
the logic required for member functions to perform
their tasks.
Image Credit: www.brighthub.com
Algorithms
•Any solvable computing problem can be solved
by executing of a series of actions in a specific
order.
•
•What is an algorithm?
A procedure for solving a problem in terms of
1. the actions to execute and
2. the order in which the actions execute
is called an algorithm.
Image Credit: openclassroom.stanford.edu
Algorithm Example
Student Morning Process
1)Get out of bed,
2)take off pajamas,
3)take a shower
4)get dressed
5)eat breakfast
6)carpool to school
Student Morning Process - Bad
1)Get out of bed,
2)take off pajamas,
3)get dressed
4)take a shower
5)eat breakfast
6)carpool to school
•Specifying the order in which statements (actions) execute is called
•program control.
•We’ll now investigate program control using C++’s control statements.
Image Credit: www.sabusinessindex.co.za
Pseudocode
Pseudocode (or “fake” code) is an artificial and
informal language that helps you develop
algorithms without having to worry about the
details of C++ language syntax.
•Pseudocode is similar to everyday English; it’s
convenient and user friendly, although it isn’t an
actual computer programming language.
Image Credit: www.bfoit.org
Pseudocode Example
•This pseudocode corresponds to the algorithm that inputs two
integers from the user, adds these integers and displays their
sum.
1 Prompt the user to enter the first integer
2 Input the first integer
4 Prompt the user to enter the second integer
5 Input the second integer
7 Add first integer and second integer, store result
8 Display result
Image Credit: www.vikingcodeschool.com
Homework #1 Pseudocode Example
1.Create 4 stoplights.
2.Give all stoplights a name.
3.Set all stoplights to red.
4.Set North stoplight to green.
5.Set South stoplight to green.
Etc.
Control Structures
•Normally, statements in a program execute one after the other in the order
in which they’re written.
•This is called sequential execution.
•Various C++ statements we’ll soon discuss enable you to specify that the next
statement to execute may be other than the next one in sequence.
•This is called transfer of control.
Image Credit: www.moroccanrubyist.com
Sequence Structure in C++
•The sequence structure is built into C++.
•Unless directed otherwise, the computer executes C++
statements one after the other in the order in which they’re
written—that is, in sequence.
•The following UML activity diagram illustrates a typical
sequence structure in which two calculations are performed in
order. C++ allows you to have as many actions as you want in a
sequence structure.
Image Credit: www.pxleyes.com
Sequence-Structure UML
Activity Diagram
•An activity diagram models the workflow (also called the activity) of a portion of a
software system.
•Such workflows may include a portion of an algorithm as shown in this diagram
•Activity diagrams are composed of special-purpose symbols, such as action state
symbols (a rectangle with its left and right sides replaced with arcs curving outward),
diamonds and small circles; these symbols are connected by transition arrows, which
represent the flow of the activity.
Sequence-Structure UML
Activity Diagram
•Activity diagrams clearly show how control
•structures operate.
•This diagram two action states that represent
actions to perform. Each action state contains
an action expression—e.g., “add grade to total” or
“add 1 to counter”—that specifies a particular action to perform.
•The arrows in the activity diagram are called transition arrows. These arrows represent
transitions, which indicate the order in which the actions represented by the action states
occur—the program that implements the activities illustrated by the activity diagram first adds
grade to total, then adds 1 to counter.
•The solid circle at the top of the diagram represents the activity’s initial state—the
beginning of the workflow before the program performs the modeled activities.
•The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram
represents the final state—the end of the workflow after the program performs its activities.
Sequence-Structure UML
Activity Diagram
•This diagram also includes rectangles with
the upper-right corners folded over.
•These are called notes in the UML—
explanatory remarks that describe the
purpose of symbols in the diagram.
•This diagram uses UML notes to show the C++ code associated with each action
state in the activity diagram.
•A dotted line connects each note with the element that the note describes.
•Activity diagrams normally do not show the C++ code that implements the activity.
We use notes for this purpose here to illustrate how the diagram relates to C++
•code.
Selection Statements in
C++
•C++ provides three types of selection statements.
•The if selection statement either performs (selects) an action if
a condition is true or skips the action if the condition is false.
•The if…else selection statement performs an action if a
condition is true or performs a different action if the condition is
false.
•The switch selection statement performs one of many different
actions, depending on the value of an integer expression.
Image Credit: www.bhamrail.com
if / if … else
•The if selection statement is a single-selection
statement because it selects or ignores a single action.
•The if…else statement is called a double-selection
statement because it selects between two different
actions.
•The switch selection statement is called a multiple-
selection statement because it selects among many
different actions.
Image Credit: en.wikipedia.org
Repetition Statements in C++
•C++ provides three types of repetition statements (also called
looping statements or loops) for performing statements
repeatedly while a condition (called the loop-continuation
condition) remains true.
•These are the while, do…while and
for statements.
•The while and for statements perform the action in their bodies
zero or more times—if the loop-continuation condition is initially
false, the action will not execute.
•The do…while statement performs the action (or group of
actions) in its body at least once.
Image Credit: potentspeaking.com
Summary of
Control Statements in C++
•C++ has only three kinds of control structures, which from this point forward we refer
to as control statements: the sequence statement, selection statements (three types—
if, if…else and switch) and repetition statements (three types—while, for and
do…while).
•Each program combines these control statements as appropriate for the algorithm
the program implements.
•We can model each control statement as an activity diagram with initial and final
states that represent a control statement’s entry point and exit point, respectively.
•These single-entry/single-exit control statements make it easy to build programs—
control statements are attached to one another by connecting the exit point of one to
the entry point of the next.
•This is similar to the way a child stacks building blocks, so we call this control-
statement stacking.
Image Credit: www.business-opportunities.biz
if Selection Statement
•Programs use selection statements to choose among alternative courses of
action.
•Pseudocode
–Suppose the passing grade on an exam is 60.
•If student’s grade is greater than or equal to 60
•Print “Passed”
–The preceding pseudocode If statement can be written in
C++ as:
if ( grade >= 60 )
cout << "Passed";
•The C++ code corresponds closely to the pseudocode. This is
one of the properties of pseudocode that make it such a useful
program development tool.
Image Credit: www.if-insurance.com
If UML Diagram
•This diagram illustrates the single-selection if
statement. It contains what is perhaps the
most important symbol in an activity diagram—
the diamond or decision symbol, which
indicates that a decision is to be made.
•A decision symbol indicates that the workflow will continue along a path determined
by the symbol’s associated guard conditions, which can
be true or false.
•Each transition arrow emerging from a decision symbol has a guard condition
(specified in square brackets above or next to the transition arrow). If a particular
guard condition is true, the workflow enters the action state to which that transition
arrow points.
•In this diagram, if the grade is greater than or equal to 60, the program prints
“Passed” to the screen, then transitions to the final state of this activity. If the grade is
less than 60, the program immediately transitions to the final state without displaying
a message.
Notes About If
•Decisions can be based on conditions containing
relational or equality operators.
•Actually, in C++, a decision can be based on any
expression—if the expression evaluates to zero, it’s
treated as false; if the expression evaluates to nonzero,
it’s treated as true.
•C++ provides the data type bool for variables that can
hold only the values true and false—each of these is a
C++ keyword.
Image Credit: www.daniellestrickland.com
if…else Double-Selection Statement
•The if single-selection statement performs an indicated action
only when the condition is true; otherwise the action is skipped.
•The if…else double-selection statement allows you to specify an
action to perform when the condition is true and a different
action to perform when the condition is false.
•Pseudocode:
–If student’s grade is greater than or equal to 60
– Print “Passed”
–Else
– Print “Failed”
Image Credit: twitter.com
if…else Double-Selection Statement
•The preceding pseudocode If…Else statement
can be written in C++ as
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
Image Credit: cupon.es
if…else double-selection statement
UML activity diagram
Software Engineering Tips!
Image Credit: searchengineland.com , www.gograph.com
•If there are several levels of indentation, each level should be
indented the same additional amount of space to promote
readability and maintainability.
•Whatever indentation convention you choose should be applied
consistently. It’s difficult to read programs that do not obey
uniform spacing conventions.
Conditional Operator (?:)
•C++ provides the conditional operator (?:), which is closely related to the if…else
statement.
•The conditional operator is C++’s only ternary operator—it takes three operands.
•The operands, together with the conditional operator, form a conditional expression.
The first operand is a condition, the second operand is the value for the entire
conditional expression if the condition is true and the third operand is the value for
the entire conditional expression if the condition is false.
•For example, the output statement
contains a conditional expression, grade >= 60 ? "Passed" : "Failed", that evaluates to
the string "Passed" if the condition grade >= 60 is true, but evaluates to "Failed" if the
condition is false.
cout << ( grade >= 60 ? "Passed" : "Failed" );
Image Credit: www.mkyong.com
Software Engineering Tips!
Image Credit: searchengineland.com
•To avoid precedence problems (and for clarity), place
conditional expressions (that appear in larger expressions) in
parentheses.
Conditional Operator (?:)
•The statement with the conditional operator performs essentially the same as the
preceding if…else statement.
•As we’ll see, the precedence of the conditional operator is low, so the parentheses in
the preceding expression are required.
•The values in a conditional expression also can be actions to execute.
•For example, the following conditional expression also prints "Passed" or "Failed":
•The preceding conditional expression is read, “If grade is greater than or equal to 60,
then cout << "Passed"; otherwise, cout << "Failed".”
•This, too, is comparable to the preceding if…else statement. Conditional expressions
can appear in some program locations where if…else statements cannot.
grade >= 60 ? cout << "Passed" : cout << "Failed";
Image Credit: www.iandevlin.com
Nested if…else Statements
•Nested if…else statements test for multiple cases by
placing if…else selection statements inside other
if…else selection statements.
•For example, the following pseudocode
if…else statement prints A for exam grades greater
than or equal to 90, B for grades in the range 80 to 89,
C for grades in the range 70 to 79, D for grades in the
range 60 to 69 and F for all other grades:
Image Credit: www.thetelecomblog.com
Nested if…else Statements
•Pseudocode
If student’s grade is greater than or equal to 90
Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”
Image Credit: sqlmag.com
C++ Code – Using If
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Image Credit: folding.stanford.edu
C++ Code – Using Else…If
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Image Credit: www.dental.pacific.edu
Software Engineering Tips!
Image Credit: www.thegeekstuff.com
•In a nested if…else statement, test the conditions that are more
likely to be true at the beginning of the nested statement. This
will enable the nested if…else statement to run faster by exiting
earlier than if infrequently occurring cases were tested first.
•A nested if…else statement can perform much faster than a
series of single-selection if statements because of the possibility
of early exit after one of the conditions is satisfied.
The Dangling-else Problem
•The C++ compiler always associates an else with the immediately preceding if unless
told to do otherwise by the placement of braces ({ and }). This behavior can lead to
what’s referred to as the dangling-else problem.
Example:
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
•Beware! This nested if…else statement does not execute as it appears.
Image Credit: www.advanceair.net
The Dangling-else Problem
Initial Code
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
What The Compiler Sees
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
Image Credit: www.pinterest.com
Solving The Dangling-else Problem
Initial Code
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
Fixed Dangling Else Problem
if ( x > 5 )
{
if ( y > 5 )
cout << "x and y are > 5";
}
else
cout << "x is <= 5";
Image Credit: www.fitlivinglifestyle.com
What We Covered Today
1.We demonstrated two of C++’s selection
statements—the if single-selection statement and
the if…else double-selection statement.
2.The if statement is used to execute a set of
statements based on a condition—if the condition
is true, the statements execute; if it isn’t, the
statements are skipped. The if…else double-
selection statement is used to execute one set of
statements if a condition is true, and another set of
statements if the condition is false.
3.We then discussed the while repetition
statement, where a set of statements are executed
repeatedly as long as a condition is true.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1.How to define a class
and use it to create an
object.
2.How to implement a
class’s behaviors as
member functions.
3.How to implement a
class’s attributes as data
members.
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
An Introduction To Software
Development Using C++
Class #9:
The ATM Machine
Problem, Part 1
What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline
Create An ATM Machine•Create a class to represent an ATM machine.
•Initialize the machine’s initial state to “machineOffline” to TRUE.
•Create 14 methods:
–load100 / num100
–load50 / num50
–load20 / num20
–load10 / num10
–load5 / num5
–load1 / num1
–currentCashContent / setMachineState
•Load the ATM machine with $1,860 ensuring that there are at least 10
bills for each of the dominations.
•Have the machine printout total amount of money contained and
number of each type of bill.
•Place the machine online Image Credit: atmequipment.com
What We Covered Today
1.Started to create an ATM
machine.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1.We’ll actually use our
new ATM machine.
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

More Related Content

PPTX
Intro To C++ - Class 10 - Control Statements: Part 2
PPTX
Intro To C++ - Class 12 - For, do … While
PPTX
Intro To C++ - Class 11 - Converting between types, formatting floating point...
PPTX
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
PDF
As Level Computer Science Book -2
PPT
Flowchart
PPT
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
PPTX
control structure
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
As Level Computer Science Book -2
Flowchart
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
control structure

What's hot (20)

PDF
problem solving and design By ZAK
PPSX
Problem solving and design
PPSX
DISE - Programming Concepts
PDF
Unit 1-problem solving with algorithm
PDF
Programming concepts By ZAK
PPTX
Ch9 Functions
PPT
Lecture 4
PDF
Flow charts
PPT
algorithm
PPTX
Type conversion, precedence, associativity in c programming
PPTX
Programming process and flowchart
DOCX
Which is not a step in the problem
PPTX
Algorithm and flowchart2010
PDF
Online Advance Excel & VBA Training in India
PDF
Visual Logic Project - 1
PPTX
Flowcharts
PPTX
Ch10 Program Organization
PDF
Sequence diagrams
PPT
Introduction to problem solving in c++
PPT
Unit 1 python (2021 r)
problem solving and design By ZAK
Problem solving and design
DISE - Programming Concepts
Unit 1-problem solving with algorithm
Programming concepts By ZAK
Ch9 Functions
Lecture 4
Flow charts
algorithm
Type conversion, precedence, associativity in c programming
Programming process and flowchart
Which is not a step in the problem
Algorithm and flowchart2010
Online Advance Excel & VBA Training in India
Visual Logic Project - 1
Flowcharts
Ch10 Program Organization
Sequence diagrams
Introduction to problem solving in c++
Unit 1 python (2021 r)
Ad

Viewers also liked (7)

PPTX
Lecture 2 variables
PPT
C++ for beginners
PDF
C++ programming intro
PDF
C++ beginner's guide ch08
PPT
2 Intro c++
PPT
Intro to c++
PPTX
Intro to C++ Basic
Lecture 2 variables
C++ for beginners
C++ programming intro
C++ beginner's guide ch08
2 Intro c++
Intro to c++
Intro to C++ Basic
Ad

Similar to Intro To C++ - Class 09 - Control Statements: Part 1 (20)

PPT
03a control structures
PPT
PPTX
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
PPTX
Control Structures, If..else, switch..case.pptx
PPTX
Flow of control C ++ By TANUJ
PDF
Chap 5 c++
PPTX
CPP04 - Selection
PPTX
control statements of clangauge (ii unit)
PPT
Basic concept of c++
PDF
Control statements
PDF
PPSX
Complete C++ programming Language Course
PPT
Lecture 1
PPT
Lecture 1
PPT
Visula C# Programming Lecture 3
PPTX
LOOPS AND DECISIONS
PPTX
Chapter 3
PPT
C++ chapter 4
PPTX
lesson 2.pptx
PPT
Flow of Control
03a control structures
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Control Structures, If..else, switch..case.pptx
Flow of control C ++ By TANUJ
Chap 5 c++
CPP04 - Selection
control statements of clangauge (ii unit)
Basic concept of c++
Control statements
Complete C++ programming Language Course
Lecture 1
Lecture 1
Visula C# Programming Lecture 3
LOOPS AND DECISIONS
Chapter 3
C++ chapter 4
lesson 2.pptx
Flow of Control

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
01-Introduction-to-Information-Management.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Institutional Correction lecture only . . .
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
master seminar digital applications in india
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Pharma ospi slides which help in ospi learning
PDF
RMMM.pdf make it easy to upload and study
PPH.pptx obstetrics and gynecology in nursing
01-Introduction-to-Information-Management.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Institutional Correction lecture only . . .
2.FourierTransform-ShortQuestionswithAnswers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Structure & Organelles in detailed.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Insiders guide to clinical Medicine.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
GDM (1) (1).pptx small presentation for students
Renaissance Architecture: A Journey from Faith to Humanism
master seminar digital applications in india
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Complications of Minimal Access Surgery at WLH
Pharma ospi slides which help in ospi learning
RMMM.pdf make it easy to upload and study

Intro To C++ - Class 09 - Control Statements: Part 1

  • 1. An Introduction To Software Development Using C++ Class #9: Control Statements: Part 1
  • 2. Next Steps •Our next step is to present the theory and principles of structured programming. • •The concepts presented here are crucial to building effective classes and manipulating objects. • •We introduce C++’s if, if…else and while statements, three of the building blocks that allow you to specify the logic required for member functions to perform their tasks. Image Credit: www.brighthub.com
  • 3. Algorithms •Any solvable computing problem can be solved by executing of a series of actions in a specific order. • •What is an algorithm? A procedure for solving a problem in terms of 1. the actions to execute and 2. the order in which the actions execute is called an algorithm. Image Credit: openclassroom.stanford.edu
  • 4. Algorithm Example Student Morning Process 1)Get out of bed, 2)take off pajamas, 3)take a shower 4)get dressed 5)eat breakfast 6)carpool to school Student Morning Process - Bad 1)Get out of bed, 2)take off pajamas, 3)get dressed 4)take a shower 5)eat breakfast 6)carpool to school •Specifying the order in which statements (actions) execute is called •program control. •We’ll now investigate program control using C++’s control statements. Image Credit: www.sabusinessindex.co.za
  • 5. Pseudocode Pseudocode (or “fake” code) is an artificial and informal language that helps you develop algorithms without having to worry about the details of C++ language syntax. •Pseudocode is similar to everyday English; it’s convenient and user friendly, although it isn’t an actual computer programming language. Image Credit: www.bfoit.org
  • 6. Pseudocode Example •This pseudocode corresponds to the algorithm that inputs two integers from the user, adds these integers and displays their sum. 1 Prompt the user to enter the first integer 2 Input the first integer 4 Prompt the user to enter the second integer 5 Input the second integer 7 Add first integer and second integer, store result 8 Display result Image Credit: www.vikingcodeschool.com
  • 7. Homework #1 Pseudocode Example 1.Create 4 stoplights. 2.Give all stoplights a name. 3.Set all stoplights to red. 4.Set North stoplight to green. 5.Set South stoplight to green. Etc.
  • 8. Control Structures •Normally, statements in a program execute one after the other in the order in which they’re written. •This is called sequential execution. •Various C++ statements we’ll soon discuss enable you to specify that the next statement to execute may be other than the next one in sequence. •This is called transfer of control. Image Credit: www.moroccanrubyist.com
  • 9. Sequence Structure in C++ •The sequence structure is built into C++. •Unless directed otherwise, the computer executes C++ statements one after the other in the order in which they’re written—that is, in sequence. •The following UML activity diagram illustrates a typical sequence structure in which two calculations are performed in order. C++ allows you to have as many actions as you want in a sequence structure. Image Credit: www.pxleyes.com
  • 10. Sequence-Structure UML Activity Diagram •An activity diagram models the workflow (also called the activity) of a portion of a software system. •Such workflows may include a portion of an algorithm as shown in this diagram •Activity diagrams are composed of special-purpose symbols, such as action state symbols (a rectangle with its left and right sides replaced with arcs curving outward), diamonds and small circles; these symbols are connected by transition arrows, which represent the flow of the activity.
  • 11. Sequence-Structure UML Activity Diagram •Activity diagrams clearly show how control •structures operate. •This diagram two action states that represent actions to perform. Each action state contains an action expression—e.g., “add grade to total” or “add 1 to counter”—that specifies a particular action to perform. •The arrows in the activity diagram are called transition arrows. These arrows represent transitions, which indicate the order in which the actions represented by the action states occur—the program that implements the activities illustrated by the activity diagram first adds grade to total, then adds 1 to counter. •The solid circle at the top of the diagram represents the activity’s initial state—the beginning of the workflow before the program performs the modeled activities. •The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram represents the final state—the end of the workflow after the program performs its activities.
  • 12. Sequence-Structure UML Activity Diagram •This diagram also includes rectangles with the upper-right corners folded over. •These are called notes in the UML— explanatory remarks that describe the purpose of symbols in the diagram. •This diagram uses UML notes to show the C++ code associated with each action state in the activity diagram. •A dotted line connects each note with the element that the note describes. •Activity diagrams normally do not show the C++ code that implements the activity. We use notes for this purpose here to illustrate how the diagram relates to C++ •code.
  • 13. Selection Statements in C++ •C++ provides three types of selection statements. •The if selection statement either performs (selects) an action if a condition is true or skips the action if the condition is false. •The if…else selection statement performs an action if a condition is true or performs a different action if the condition is false. •The switch selection statement performs one of many different actions, depending on the value of an integer expression. Image Credit: www.bhamrail.com
  • 14. if / if … else •The if selection statement is a single-selection statement because it selects or ignores a single action. •The if…else statement is called a double-selection statement because it selects between two different actions. •The switch selection statement is called a multiple- selection statement because it selects among many different actions. Image Credit: en.wikipedia.org
  • 15. Repetition Statements in C++ •C++ provides three types of repetition statements (also called looping statements or loops) for performing statements repeatedly while a condition (called the loop-continuation condition) remains true. •These are the while, do…while and for statements. •The while and for statements perform the action in their bodies zero or more times—if the loop-continuation condition is initially false, the action will not execute. •The do…while statement performs the action (or group of actions) in its body at least once. Image Credit: potentspeaking.com
  • 16. Summary of Control Statements in C++ •C++ has only three kinds of control structures, which from this point forward we refer to as control statements: the sequence statement, selection statements (three types— if, if…else and switch) and repetition statements (three types—while, for and do…while). •Each program combines these control statements as appropriate for the algorithm the program implements. •We can model each control statement as an activity diagram with initial and final states that represent a control statement’s entry point and exit point, respectively. •These single-entry/single-exit control statements make it easy to build programs— control statements are attached to one another by connecting the exit point of one to the entry point of the next. •This is similar to the way a child stacks building blocks, so we call this control- statement stacking. Image Credit: www.business-opportunities.biz
  • 17. if Selection Statement •Programs use selection statements to choose among alternative courses of action. •Pseudocode –Suppose the passing grade on an exam is 60. •If student’s grade is greater than or equal to 60 •Print “Passed” –The preceding pseudocode If statement can be written in C++ as: if ( grade >= 60 ) cout << "Passed"; •The C++ code corresponds closely to the pseudocode. This is one of the properties of pseudocode that make it such a useful program development tool. Image Credit: www.if-insurance.com
  • 18. If UML Diagram •This diagram illustrates the single-selection if statement. It contains what is perhaps the most important symbol in an activity diagram— the diamond or decision symbol, which indicates that a decision is to be made. •A decision symbol indicates that the workflow will continue along a path determined by the symbol’s associated guard conditions, which can be true or false. •Each transition arrow emerging from a decision symbol has a guard condition (specified in square brackets above or next to the transition arrow). If a particular guard condition is true, the workflow enters the action state to which that transition arrow points. •In this diagram, if the grade is greater than or equal to 60, the program prints “Passed” to the screen, then transitions to the final state of this activity. If the grade is less than 60, the program immediately transitions to the final state without displaying a message.
  • 19. Notes About If •Decisions can be based on conditions containing relational or equality operators. •Actually, in C++, a decision can be based on any expression—if the expression evaluates to zero, it’s treated as false; if the expression evaluates to nonzero, it’s treated as true. •C++ provides the data type bool for variables that can hold only the values true and false—each of these is a C++ keyword. Image Credit: www.daniellestrickland.com
  • 20. if…else Double-Selection Statement •The if single-selection statement performs an indicated action only when the condition is true; otherwise the action is skipped. •The if…else double-selection statement allows you to specify an action to perform when the condition is true and a different action to perform when the condition is false. •Pseudocode: –If student’s grade is greater than or equal to 60 – Print “Passed” –Else – Print “Failed” Image Credit: twitter.com
  • 21. if…else Double-Selection Statement •The preceding pseudocode If…Else statement can be written in C++ as if ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; Image Credit: cupon.es
  • 23. Software Engineering Tips! Image Credit: searchengineland.com , www.gograph.com •If there are several levels of indentation, each level should be indented the same additional amount of space to promote readability and maintainability. •Whatever indentation convention you choose should be applied consistently. It’s difficult to read programs that do not obey uniform spacing conventions.
  • 24. Conditional Operator (?:) •C++ provides the conditional operator (?:), which is closely related to the if…else statement. •The conditional operator is C++’s only ternary operator—it takes three operands. •The operands, together with the conditional operator, form a conditional expression. The first operand is a condition, the second operand is the value for the entire conditional expression if the condition is true and the third operand is the value for the entire conditional expression if the condition is false. •For example, the output statement contains a conditional expression, grade >= 60 ? "Passed" : "Failed", that evaluates to the string "Passed" if the condition grade >= 60 is true, but evaluates to "Failed" if the condition is false. cout << ( grade >= 60 ? "Passed" : "Failed" ); Image Credit: www.mkyong.com
  • 25. Software Engineering Tips! Image Credit: searchengineland.com •To avoid precedence problems (and for clarity), place conditional expressions (that appear in larger expressions) in parentheses.
  • 26. Conditional Operator (?:) •The statement with the conditional operator performs essentially the same as the preceding if…else statement. •As we’ll see, the precedence of the conditional operator is low, so the parentheses in the preceding expression are required. •The values in a conditional expression also can be actions to execute. •For example, the following conditional expression also prints "Passed" or "Failed": •The preceding conditional expression is read, “If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed".” •This, too, is comparable to the preceding if…else statement. Conditional expressions can appear in some program locations where if…else statements cannot. grade >= 60 ? cout << "Passed" : cout << "Failed"; Image Credit: www.iandevlin.com
  • 27. Nested if…else Statements •Nested if…else statements test for multiple cases by placing if…else selection statements inside other if…else selection statements. •For example, the following pseudocode if…else statement prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades: Image Credit: www.thetelecomblog.com
  • 28. Nested if…else Statements •Pseudocode If student’s grade is greater than or equal to 90 Print “A” Else If student’s grade is greater than or equal to 80 Print “B” Else If student’s grade is greater than or equal to 70 Print “C” Else If student’s grade is greater than or equal to 60 Print “D” Else Print “F” Image Credit: sqlmag.com
  • 29. C++ Code – Using If if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; Image Credit: folding.stanford.edu
  • 30. C++ Code – Using Else…If if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; Image Credit: www.dental.pacific.edu
  • 31. Software Engineering Tips! Image Credit: www.thegeekstuff.com •In a nested if…else statement, test the conditions that are more likely to be true at the beginning of the nested statement. This will enable the nested if…else statement to run faster by exiting earlier than if infrequently occurring cases were tested first. •A nested if…else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.
  • 32. The Dangling-else Problem •The C++ compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what’s referred to as the dangling-else problem. Example: if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5"; else cout << "x is <= 5"; •Beware! This nested if…else statement does not execute as it appears. Image Credit: www.advanceair.net
  • 33. The Dangling-else Problem Initial Code if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5"; else cout << "x is <= 5"; What The Compiler Sees if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5"; else cout << "x is <= 5"; Image Credit: www.pinterest.com
  • 34. Solving The Dangling-else Problem Initial Code if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5"; else cout << "x is <= 5"; Fixed Dangling Else Problem if ( x > 5 ) { if ( y > 5 ) cout << "x and y are > 5"; } else cout << "x is <= 5"; Image Credit: www.fitlivinglifestyle.com
  • 35. What We Covered Today 1.We demonstrated two of C++’s selection statements—the if single-selection statement and the if…else double-selection statement. 2.The if statement is used to execute a set of statements based on a condition—if the condition is true, the statements execute; if it isn’t, the statements are skipped. The if…else double- selection statement is used to execute one set of statements if a condition is true, and another set of statements if the condition is false. 3.We then discussed the while repetition statement, where a set of statements are executed repeatedly as long as a condition is true. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 36. What We’ll Be Covering Next Time 1.How to define a class and use it to create an object. 2.How to implement a class’s behaviors as member functions. 3.How to implement a class’s attributes as data members. Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
  • 37. An Introduction To Software Development Using C++ Class #9: The ATM Machine Problem, Part 1
  • 38. What’s In Your C++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline
  • 39. Create An ATM Machine•Create a class to represent an ATM machine. •Initialize the machine’s initial state to “machineOffline” to TRUE. •Create 14 methods: –load100 / num100 –load50 / num50 –load20 / num20 –load10 / num10 –load5 / num5 –load1 / num1 –currentCashContent / setMachineState •Load the ATM machine with $1,860 ensuring that there are at least 10 bills for each of the dominations. •Have the machine printout total amount of money contained and number of each type of bill. •Place the machine online Image Credit: atmequipment.com
  • 40. What We Covered Today 1.Started to create an ATM machine. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 41. What We’ll Be Covering Next Time 1.We’ll actually use our new ATM machine. Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

Editor's Notes