Chapter 3
More Flow Of Control
Boolean Expression
• Expression that yields bool result
• Include:
6 Relational Operators
<
<=
>
>=
==
3 Logical Operators
!
&&
||
!=
Boolean Expression (examples)
taxRate is over 25% and income is less than
$20000
temperature is less than or equal to 75 or humidity
is less than 70%
age is between 21 and 60
age is 21 or 22
Boolean Expression (examples)
(taxRate > .25) && (income < 20000)
(temperature <= 75) || (humidity < .70)
(age >= 21) && (age <= 60)
(age == 21) || (age == 22)
Precedence Chart
• ++, --, !, - (unary minus), + (unary
plus)
• *, /, %
• + (addition), - (subtraction)
• <<, >>
• <, <=, >, >=
• ==, !=
• &&
• ||
• =
Highest
Lowest
“Short-Circuit” Evaluation
• C++ uses short circuit evaluation of logical
expressions
• This means logical expressions are
evaluated left to right and evaluation stops
as soon as the final truth value can be
determined
Short-Circuit Example
(age > 50) && (height > 60)
When age is less than 50, evaluation can stop now because result of
&& is only true when both sides are true. It is already determined
that the entire expression will be false.
(age > 50) || (height > 60)
When age is greater than 50, evaluation can stop now because result
of is true if one side is true. It is already determined that the entire
expression will be true.
However, when age is less than 50, evaluation must continue because
result of the entire expression has not been determined.
Short-Circuit Benefits
• One Boolean expression can be placed
first to “guard” a potentially unsafe
operation in a second Boolean expression
• Time is saved in evaluation of complex
expressions using operators || and &&
• Optimize code by placing most telling
condition first.
Boolean evaluation on Arithmetic
Expressions
• All yields either 1 or 0.
– Thus, !5 = 0, !(-5) = 0, !0 = 1
• In C++, these values (0 and 1) can be
used arithmetically, there is no difference
between a 1 derived from !5 and 1 derived
from 3 - 2.
Enumeration Types
• Is a type whose values are defined by a
list of constants type int.
enum Fruits {ORANGE, GRAPE, APPLE};
Enumeration Types (Notes)
• Sets must be finite
• Members are called enumerators- unique identifier
• Members are constants of type int with default value
starting from 0
• Can initialize values to other than 0:
– enum sizes {small, medium = 10, large = 20}
• Values need not be unique
•
enum economy {recession = -1, depression = -1, growth = 1}
• Positive or negative numbers can be associated
– enum economy {recession = -1, depression = -2, growth = 1}
• Can declare type and variable of that type at same time.
– enum economy {recession = -1, depression = -2, growth = 1} bear ;
Enumeration Types (Notes)
• Can use in switch as case label->integral constants
• Can compare 2 different enumerated type variables by
casting to int
– Ex: int(jan_len) < int(false)
• Cannot read or write directly because the compiler
doesn’t know the rules for this type.
• Why use enumerated types?
– Used for program clarity
• Compiler will do type checking - prevent mixing types
– Use 6 for Saturday and 6 for Date allows incorrect comparison.
Multiway Branches
• When there are more than 2 options to
consider
• Used in:
– Nested if statements
– Multiway if-else statements
– switch statements
Nested if Statements
•
•
•
An if statement nested inside another if
statement
Indent each statement.
Use braces for clarity.
Dangling else in nested if statements
• Compiler matches else with most recent if:
if (fuel-gauge_reading < 0.75)
if (fuel-gauge_reading <0.25)
cout<<”Fuel very low. Caution!\n”;
else
cout<<”Fuel over 3/4. Don’t stop now!\n”;
If fuel is 0.8, there is no ouput.
If fuel is 0.5, output is:
Fuel over 3/4. Don’t stop now!
• Need to force compiler to match if-else correctly.
Dangling else in nested if statements
(Solutions)
• Use braces to set off inner else
if (fuel-gauge_reading < 0.75)
{
if (fuel-gauge_reading <0.25)
cout<<”Fuel very low. Caution!\n”;
}
else
cout <<”Fuel over 3/4. Don’t stop now!\n”;
• Use null statement for else
if (fuel-gauge_reading < 0.75)
if (fuel-gauge_reading <0.25)
cout<<”Fuel very low. Caution!\n”;
else;
else
cout <<”Fuel over 3/4. Don’t stop now!\n”;
Multiway if-else Statements
• Is another form of nested if
• EXACTLY 1 of these statements will be executed.
• Syntax
if ( Expression1 )
Statement1
else if ( Expression2 )
Statement2
.
.
.
else if ( ExpressionN )
StatementN
else
Statement N+1
Multiway if-else Statements (Notes)
• Order is important.
if (grade<70) cout<<’F’;
else if ( grade>=70) cout<<‘C’;
else if (grade>=80) cout<<‘B’;
else cout<<‘A’;
if (grade>=90) cout<<‘A’;
else if (grade>=80) cout<<‘B’;
else if (grade>=70) cout<<‘C’
else cout<<‘F’;
If grade is 82: C
If grade is 82: B
• More efficient to put most probable result
first.
switch Statement
• Replaces the multiple alternative if
statement
• Work with exact value only
• Computer evaluates value of grade and
finds case label that matches that value.
• Value must be of integral type (enum, int,
char, bool)
• Will not work on string, double or float.
• For efficiency, put most likely options first.
switch Statement (Syntax)
switch ( Integral Expression )
{
case Constant1 :
Statement(s);
// optional
case Constant2 :
Statement(s);
// optional
.
.
.
default :
Statement(s);
}
// optional
// optional
switch Statement (break use)
• Switch statement does action after case
statement until it reaches break.
• No {} needed for multiple statements.
• If no break occurs in that case, execution
will “fall through” and do the next case,
etc. until a break is reached.
• break statement returns control to next
line outside switch statement.
switch Statement (default case)
default can be used for values not
represented by any case label.
Only 1 default statement in a switch.
switch Statement (Example)
char finalGrade;
…. // get value for finalGrade
switch ( finalGrade )
{
case ‘A’ :
cout << “Excellence!” << endl ;
break ;
case ‘B’ :
cout << “Good!” << endl ;
break ;
case ‘C’ :
cout << “Pass!” << endl ;
break ;
case ‘D’ :
cout << “Sorry!” << endl ;
case ‘F’ :
cout << “You failed!” << endl ;
break ;
default :
cout << “It is not a grade! “ << endl ;
break ; // not needed
}
finalGrade
Output
A
B
C
Excellence!
Good!
Pass!
D
Sorry!
You failed!
You failed!
It is not a grade
F
Anything else
break and exit
• break exits that particular control
statement. Used to break out of loops,
switches.
• exit exits the program and can return a
value EXIT_SUCCESS and
EXIT_FAILURE (defined in stdlib.h) to the
invoking process. (Not recommend to use
in this class)
Blocks
•
A compound statement which contains local variables
– denoted by braces {}.
Scope:
•
–
–
•
•
•
Visibility: Local variables can only be seen within the block.
Other functions and the main program do not know they exist.
Therefore, there is no conflict and other functions or programs
can use variables of the same name.
Viability: Local variables are created and destroyed within the
block. Saves on memory.
Block allows use of global variables and local
variables.
local variable: visibility and viability is within block
only!
Blocks can be nested inside other blocks.
Blocks (Example)
float price 50.0;
int num;
… // Get num
{
float subtotal;
subtotal = price * num;
}
cout << “The total for “ << num
<< “ is “ << subtotal;
float price 50.0;
int num;
… // Get num
{
float subtotal;
subtotal = price * num;
cout << “The total for “ << num
<< “ is “ << subtotal;
}
Syntax error!
Legal
Chapter 2 Review
• Open Chapter 2 slides
• Review While and Do-While Loops
• Review Increment and Decrement
FOR Loop
Used when
Syntax:
for (initialize; test condition; update)
{
… //loop body
}
Example:
int sum = 0;
for (int i=1; i<=10; i++) //i is a local variable
sum = sum + i;
FOR Loop (Notes)
Can use commas to do more than 1 action in any part
for(i=1,sum=0;i<10; sum+=i++); //complete loop-no body needed
Can eliminate any part of loop
for (; Test; Action)- start missing - allows the same loop to be used for different starting points as
long as initialized before used. (allows flexibility)
Ex: cin>>i;
for(; i<10; i++);
Increment in loop rather than in loop body
for (i=0; i<10; i++)
Omit everything
for (;;) // (infinite loop)
{
//body of loop
if (I % 5 == 0) break; // use break to exit loop
}
Accidentally eliminating loop body by placing a semicolon at the end
for (i=0; i<10; i++);
cout << i << endl;
// Only 10 in the output
Designing Loops
•
What kind of loop to use
–
–
–
–
–
•
Must iterate at least once?
Must iterate at least never?
Numerically increases/decreases by a set amount?
Know exactly how many times to execute.
Execution depends on events?
Do-While
While
While
For
While
What do we need to know?
–
–
–
What is the process being repeated?
THE BODY
How must the process be initialized and updated? INITIALIZATION.
What is the ending condition for our loop? EXIT CONDITIONS
Loop For Sums and Products
• Used when a value (accumulator) is to be
increased/decreased by the new value.
• Notes:
– Accumulator for a sum must be initialized to 0.
– Accumulator for a product must be initialized to
nonzero.
Loop Ending
• List headed by size
Input list known beforehand
• Count controlled loop
number of iterations known before loops begin
• Ask before iteration
Used for menus and for repeated processing
• Using SENTINELS
A special value which has no valid meaning to the program and is
entered by the user to terminate a loop
• Running out of input
Cannot read any more input from a file
• Using boolean flag
Raise flag when something happened
Nest Loops
• A loop within a loop.
• Example:
for (int i=0; i<3; i++)
{
cout << “Row# “ << i << “: ”;
for (int j=0; j<5; j++)
cout << j << “ ”;
cout << endl;
}
Row# 0: 0 1 2 3 4
Row# 1: 0 1 2 3 4
Row# 2: 0 1 2 3 4
Debugging Loops
• Set breakpoint at the beginning of the
loop. Check the LCV value when this
breakpoint is hit.
• Set breakpoint at the first line of the loop
body. Check if the execution stops at this
breakpoint.
• Repeat 2 above steps would help to find
problem with the loops
© Copyright 2025 Paperzz