0% found this document useful (0 votes)
13 views

Chap 2 CPP 6 TH

The document discusses various concepts related to flow of control in C++ including boolean expressions, branching mechanisms like if-else and switch statements, loops like while, do-while and for loops, and nesting of these structures. It provides examples and syntax for evaluating boolean expressions and precedence rules, if-else statements with optional else clauses, multiway if-else statements, switch statements with case labels and fall through, conditional operators, while, do-while and for loop syntax and examples. It also discusses nesting of statements and common pitfalls to avoid.

Uploaded by

BT Me
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chap 2 CPP 6 TH

The document discusses various concepts related to flow of control in C++ including boolean expressions, branching mechanisms like if-else and switch statements, loops like while, do-while and for loops, and nesting of these structures. It provides examples and syntax for evaluating boolean expressions and precedence rules, if-else statements with optional else clauses, multiway if-else statements, switch statements with case labels and fall through, conditional operators, while, do-while and for loop syntax and examples. It also discusses nesting of statements and common pitfalls to avoid.

Uploaded by

BT Me
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 2

Flow of Control

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Learning Objectives
• Boolean Expressions
– Building, Evaluating & Precedence Rules
• Branching Mechanisms
– if-else
– switch
– Nesting if-else
• Loops
– While, do-while, for
– Nesting loops
• Introduction to File Input
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-2
Boolean Expressions:
Display 2.1 Comparison Operators
• Logical Operators
– Logical AND (&&)
– Logical OR (||)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-3


Evaluating Boolean Expressions
• Data type bool
– Returns true or false
– true, false are predefined library consts

• Truth tables
– Display 2.2 next slide

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-4


Evaluating Boolean Expressions: Display 2.2
Truth Tables

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-5


Display 2.3
Precedence of Operators (1 of 4)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-6


Display 2.3
Precedence of Operators (2 of 4)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-7


Display 2.3
Precedence of Operators (3 of 4)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-8


Display 2.3
Precedence of Operators (4 of 4)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-9


Precedence Examples
• Arithmetic before logical
– x + 1 > 2 || x + 1 < -3 means:
• (x + 1) > 2 || (x + 1) < -3

• Short-circuit evaluation
– (x >= 0) && (y > 1)
– Be careful with increment operators!
• (x > 1) && (y++)

• Integers as boolean values


– All non-zero values à true
– Zero value à false

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-10


Strong Enum
• C++11 introduces strong enums or enum
classes
– Does not act like an integer
– Examples
enum class Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
enum class Weather { Rain, Sun };
Days d = Days::Tue;
Weather w = Weather::Sun;

– Illegal: if (d == 0)
– Legal: if (d == Days::Wed)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-11


Branching Mechanisms
• if-else statements
– Choice of two alternate statements based
on condition expression
– Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-12


if-else Statement Syntax
• Formal syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
• Note each alternative is only
ONE statement!
• To have multiple statements execute in
either branch à use compound statement

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-13


Compound/Block Statement
• Only "get" one statement per branch
• Must use compound statement { }
for multiples
– Also called a "block" stmt
• Each block should have block statement
– Even if just one statement
– Enhances readability

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-14


Compound Statement in Action
• Note indenting in this example:
if (myScore > yourScore)
{
cout << "I win!\n";
wager = wager + 100;
}
else
{
cout << "I wish these were golf scores.\n";
wager = 0;
}

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-15


Common Pitfalls
• Operator "=" vs. operator "=="
• One means "assignment" (=)
• One means "equality" (==)
– VERY different in C++!
– Example:
if (x = 12) ßNote operator used!
Do_Something
else
Do_Something_Else

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-16


The Optional else
• else clause is optional
– If, in the false branch (else), you want "nothing" to happen,
leave it out
– Example:
if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;

– Note: nothing to do for false condition, so there is no else


clause!
– Execution continues with cout statement

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-17


Nested Statements
• if-else statements contain smaller statements
– Compound or simple statements (we’ve seen)
– Can also contain any statement at all, including another if-
else stmt!
– Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
• Note proper indenting!

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-18


Multiway if-else
• Not new, just different indenting
• Avoids "excessive" indenting
– Syntax:

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-19


Multiway if-else Example

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-20


The switch Statement
• A statement for controlling multiple branches
• Can do the same thing with if statements but
sometimes switch is more convenient
• Uses controlling expression which returns bool
data type (true or false)
• Syntax:
– Next slide

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-21


switch Statement Syntax

The controlling expression must be integral! This includes char.


Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-22
The switch Statement in Action

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-23


The switch: multiple case labels
• Execution "falls thru" until break
– switch provides a "point of entry"
– Example:
case 'A':
case 'a':
cout << "Excellent: you got an
"A"!\n";
break;
case 'B':
case 'b':
cout << "Good: you got a "B"!\n";
break;
– Note multiple labels provide same "entry"

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-24


switch Pitfalls/Tip
• Forgetting the break;
– No compiler error
– Execution simply "falls thru" other cases until
break;

• Biggest use: MENUs


– Provides clearer "big-picture" view
– Shows menu structure effectively
– Each branch is one menu choice

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-25


switch Menu Example
• Switch stmt "perfect" for menus:
switch (response)
{
case 1:
// Execute menu option 1
break;
case 2:
// Execute menu option 2
break;
case 3:
// Execute menu option 3
break;
default:
cout << "Please enter valid response.";
}

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-26


Conditional Operator
• Also called "ternary operator"
– Allows embedded conditional in expression
– Essentially "shorthand if-else" operator
– Example:
if (n1 > n2)
max = n1;
else
max = n2;
– Can be written:
max = (n1 > n2) ? N1 : n2;
• "?" and ":" form this "ternary" operator

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-27


Loops
• 3 Types of loops in C++
– while
• Most flexible
• No "restrictions"

– do-while
• Least flexible
• Always executes loop body at least once

– for
• Natural "counting" loop

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-28


while Loops Syntax

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-29


while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}

– Loop body executes how many times?

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-30


do-while Loop Syntax

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-31


do-while Loop Example
• count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition

– Loop body executes how many times?


– do-while loops always execute body at least once!

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-32


while vs. do-while
• Very similar, but…
– One important difference
• Issue is "WHEN" boolean expression is checked
• while: checks BEFORE body is executed
• do-while: checked AFTER body is executed

• After this difference, they’re


essentially identical!
• while is more common, due to it’s
ultimate "flexibility"

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-33


Comma Operator
• Evaluate list of expressions, returning
value of the last expression
• Most often used in a for-loop
• Example:
first = (first = 2, second = first + 1);
– first gets assigned the value 3
– second gets assigned the value 3
• No guarantee what order expressions will
be evaluated.

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-34


for Loop Syntax
for (Init_Action; Bool_Exp; Update_Action)
Body_Statement

• Like if-else, Body_Statement can be


a block statement
– Much more typical

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-35


for Loop Example
• for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}

• How many times does loop body execute?


• Initialization, loop condition and update all
"built into" the for-loop structure!
• A natural "counting" loop

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-36


Loop Issues
• Loop’s condition expression can be ANY boolean
expression
• Examples:
while (count<3 && done!=0)
{
// Do something
}
for (index=0;index<10 && entry!=-99)
{
// Do something
}

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-37


Loop Pitfalls: Misplaced ;
• Watch the misplaced ; (semicolon)
– Example:
while (response != 0) ;ß
{
cout << "Enter val: ";
cin >> response;
}
– Notice the ";" after the while condition!
• Result here: INFINITE LOOP!

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-38


Loop Pitfalls: Infinite Loops
• Loop condition must evaluate to false at
some iteration through loop
– If not à infinite loop.
– Example:
while (1)
{
cout << "Hello ";
}
– A perfectly legal C++ loop à always infinite!
• Infinite loops can be desirable
– e.g., "Embedded Systems"

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-39


The break and continue Statements

• Flow of Control
– Recall how loops provide "graceful" and clear flow of
control in and out
– In RARE instances, can alter natural flow
• break;
– Forces loop to exit immediately.
• continue;
– Skips rest of loop body
• These statements violate natural flow
– Only used when absolutely necessary!
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-40
Nested Loops
• Recall: ANY valid C++ statements can be
inside body of loop
• This includes additional loop statements!
– Called "nested loops"
• Requires careful indenting:
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;
– Notice no { } since each body is one statement
– Good style dictates we use { } anyway

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-41


Introduction to File Input
• We can use cin to read from a file in a manner
very similar to reading from the keyboard
• Only an introduction is given here, more
details are in chapter 12
– Just enough so you can read from text files and
process larger amounts of data that would be too
much work to type in

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-42


Opening a Text File
• Add at the top
#include <fstream>
using namespace std;

• You can then declare an input stream just as you


would declare any other variable.
ifstream inputStream;

• Next you must connect the inputStream variable to a


text file on the disk.
inputStream.open("filename.txt");

• The “filename.txt” is the pathname to a text file or a


file in the current directory
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-43
Reading from a Text File
• Use
inputStream >> var;
• The result is the same as using cin >> var
except the input is coming from the text file
and not the keyboard
• When done with the file close it with
inputStream.close();

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-44


File Input Example (1 of 2)
• Consider a text file named player.txt with the
following text

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-45


File Input Example (2 of 2)

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-46


Summary 1
• Boolean expressions
– Similar to arithmetic à results in true or false
• C++ branching statements
– if-else, switch
– switch statement great for menus
• C++ loop statements
– while
– do-while
– for

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-47


Summary 2
• do-while loops
– Always execute their loop body at least once
• for-loop
– A natural "counting" loop

• Loops can be exited early


– break statement
– continue statement
– Usage restricted for style purposes
• Reading from a text file is similar to reading
from cin
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-48

You might also like