Transcript Slide 1

Control Statements: Part I
Chapter 4
1
Introduction
• Three building blocks for C++ control
– Sequence structure
– Selection structure
– Repetition structure
• Operators
– Assignment operators
– Increment/decrement operators
2
Algorithms
• Algorithm is a procedure of solving a
problem in terms of
– The actions to execute and
– The order in which these actions execute
• Program control
– Specify the order in which statements execute
3
Pseudocode
• Pseudocode
– An artificial and informal language that helps
programmer develop algorithms
– Normally describes only executable statements (not
variable declarations)
Prompt the user to enter 1st integer
Input the first integer
Prompt the user to enter the 2nd integer
Input the 2nd integer
Add first integer and second integer, store results
Display result
4
Control Structures
• Sequential execution
– Execute one statement after the other in which they are written
• Transfer of control
– Next one in sequence may not be next statement to execute
– Indiscriminate use of transfer of control (goto statement) cause
tremendous difficulty for software developers
• Structured programming (Bohm and Jocopini)
–
–
–
–
Goto elimination
More likely to be bug free
Clear, easier to debug and modify
Reduced development time
• Control structures
– Sequence structure
– Selection structure
– Repetition structure
5
Sequence Structure in C++
Initial
state
Notes
Action state
symbol
Sequence-structure
activity diagram
Final
state
6
Selection Statements in C++
• Single-selection statement (if)
– Selects or ignores a single action
• Double-selection statement (if…else)
– Selects between two different actions
• Multiple-selection statement (switch)
– Selects among many different actions (groups
of actions)
7
Repetition Statements in C++
• Performs statements repeatedly as long as a
condition (loop-continuation condition) remains
true
• Three types of repetition statements
– while
• Perform the action(s) in its body zero or more times
– For
• Perform the action(s) in its body zero or more times
– do…while
• Perform the action(s) in its body at least once
8
C++ keywords
Keywords common to C and C++ languages
auto
continue
enum
if
short
switch
volatile
break
default
extern
int
signed
typedef
while
case
do
float
long
sizeof
union
char
double
for
register
static
unsigned
const
else
goto
return
struct
void
C++ only keywords
and
bool
delete
friend
not
private
template
typeid
xor
and_eq
catch
dynamic_cast
inline
not_eq
protected
this
typename
xor_eq
asm
class
explicit
mutable
operator
public
throw
using
bitand
compl
export
namespace
or
reinterpret_cast
true
virtual
bitor
const_cast
false
new
or_eq
static_cast
try
wchar_t
9
Common Programming Errors Related to Keywords
• Using a keyword as an identifier is a
syntax error
• Spelling a keyword with any uppercase
letters is a syntax error. All of C++’s
keywords contain only lowercase letters
10
Connect Control Statements
• Model each control statement as an activity
diagram
– Initial state represents the entry point
– Final state represents the exit point
• Control-statement stacking
– Control statements are attached to one another by
connecting the exit point of one to the entry point of
the next
• Control-statement nesting
– One control statement is contained inside another
11
if Single-selection Statement
Associated guard condition
Evaluates to be true or false
Decision
symbol
Single-entry
/single-exit
Transition
arrow
Guard conditions can be boolean expressions or any
expressions that evaluate to a number.
Boolean expression: true or false
Any expression: zero (false), non-zero (true)
12
if…else Double-selection Statement
Conditional operator (?:): only ternary operator in C++
cout << (grade>=60 ? “Passed” : “Failed”);
13
Nested if…else Statements
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";
14
Cont’
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";
Programming Tips
A nested if…else statement can perform much faster than a series of
single-selection if statements because of the possible early exit
In a nested if…else statement, test the most likely condition first to
maximize the chance of early exit
15
Dangling-else Problem
The C++ compiler always associates an else with the immediately
preceding if unless told to do otherwise by the placements of
braces. This behavior can lead to dangling-else problem.
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
Danglingelse
else
cout << "x is <= 5";
if ( x > 5 )
{
if ( y > 5 )
Correct
cout << "x and y are > 5";
}
else
cout << "x is <= 5";
16
Blocks
• if selection statement and if…else statement
normally expect only one body statement
• Enclose several statements in the body of an if or in
either part of an if…else with a pair of curly braces
• A set of statements contained in a pair of braces is called
compound statement or a block
–
–
–
A block can be placed anywhere in a program that a single statement can be placed
Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic
errors
Always putting the braces in an if…else statement helps prevent their accidental omission
• Null Statement (Empty statement)
–
–
Placing a semicolon (;) where a statement would normally be
Placing a semicolon after the condition in an if statement leads to a logic error in singleselection if statements and a syntax error in double selection if…else statements (when the if
part contains an actual body statement)
17
while Repetition Statement
Joins the transitions
from the initial state
and the action state
18
Infinite Loop
Cause:
No action in the while body to cause the condition to
become false.
Results:
Repetition statement never terminates
Program appears to “hang” or “freeze”
Infinite
Loop
int i = 1;
int factorial = 1;
while(i>0)
{
factorial = factorial*i;
i++;
}
19
Formulating Algorithms: Counter-Controlled Repetition
Definite Repetition
Problem statement:
A class of ten students took a quiz. The grades for the quiz are
available to you. Calculate and display the total of all student grades
and the class average on the quiz.
Repetition terminates when
counter exceeds 10
Set total to zero
Set grade counter to one
Pseudocode
While grade counter is less than or equal to ten
Prompt the user to enter the next grade
Input the next grade
Add the grade into the total
Add one to the grade counter
Update the
counter
Set the class average to the total divided by ten
Print the total of the grades for all students in the class
Print the class average
20
Off-by-one-error
Cause:
Use a loop’s counter-control variable in a
calculation after the loop
Result:
The loop terminates when the counter’s value is
one higher than its last legitimate value (i.e., 11 in
the case of counting from 1 to 10)
21
Formulating Algorithms: Sentinel-Controlled Repetition
Problem statement:
Develop a class average algorithm that process grades for an
arbitrary number of students each time it is run.
Initialize total to zero
Initialize counter to zero //avoid off-by-one-error
Prompt the user to enter the first grade
Input the first grade (possibly the sentinel)
While the user has not yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Prompt the user to enter the next grade
Input the next grade (possibly the sentinel)
Sentinel
value is -1
Proper message
with information
on sentinel value
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the total of the grades for all students in the class
Print the class average
Else
Print “No grades were entered”
22
Sentinel-Controlled Repetition vs
Counter-Controlled Repetition
• Counter-controlled repetition
– Each iteration of the while statement reads a
value from the user, for the specified number
of iterations
• Sentinel-controlled repetition
– The program reads the first value before
reaching the while
– The body of while may never execute (e.g.,
no grades were entered)
23
Explicit and Implicit Conversion
between Fundamental Types
double average;
average = static_cast<double> (total)/gradeCounter;
Explicit conversion is done
by unary cast operator
gradeCounter is promoted to
double (implicit conversion)
24
Formatting for Floating-Point Numbers
• Nonparameterized stream manipulator
– endl, fixed, showpoint, left,
right(default)
– Do not require <iomanip> header file
• Parameterized stream manipulator
– Require #include <iomanip>
– cout << “Class average is “ <<
setprecision(2) << fixed << average <<
endl;
Round number to 2
decimal places
25
Formulating Algorithms: Nested Control Statements
Problem statement:
You have been given a list of these 10 students. Next to each name is written a 1 if the student
passed or a 2 if the student failed. You have been asked to summarized the results in terms of
number of passes and fails.
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
While student counter is less than or equal to 10
Prompt the user to enter the next exam result
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
If…else is
nested in
while body
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
26
Arithmetic Assignment Operators
Assignment
operator
Sample
expression
Explanation
Assigns
Assume: int c=3, d=5, e=4, f=6, g=12;
+=
c += 7
c=c+7
10 to c
-=
d -= 4
d=d-4
1 to d
*=
e *= 5
e=e*5
20 to e
/=
f /= 3
f=f/3
2 to f
%=
g %= 9
g=g%9
3 to g
27
Increment and Decrement Operators
Operator
Called
Sample
expression
Explanation
++
Preincrement
++a
Increment a by 1, then use the
new value of a in the expression
in which it resides
++
Postincrement
a++
Use the current value of a in the
expression in which a resides,
then increment a by 1
--
Predecrement
--b
Decrement b by 1, then use the
new value of b in the expression
in which it resides
--
Postdecrement
b--
Use the current value of b in the
expression in which b resides,
then decrement b by 1
28
Example: Preimcrementing and Postincrementing
int main()
{
int c;
// demonstrate postincrement
c = 5; // assign 5 to c
cout << c << endl; // print 5
cout << c++ << endl; // print 5 then postincrement
cout << c << endl; // print 6
cout << endl; // skip a line
// demonstrate preincrement
c = 5; // assign 5 to c
cout << c << endl; // print 5
cout << ++c << endl; // preincrement then print 6
cout << c << endl; // print 6
return 0; // indicate successful termination
} // end main
29
Operator Precedence
Operators
Associativity
Type
()
Left to right
Parenthesis
++ -- static_cast<type>()
Left to right
Unary (postfix)
++ -- + -
Right to left
Unary (prefix)
* / %
Left to right
Multiplicative
+ -
Left to right
Additive
<< >>
Left to right
Insertion/extraction
< <= > >=
Left to right
Relational
== !=
Left to right
Equality
?:
Right to left
Conditional
= += -= *= /= %=
Right to left
Assignment
30