Chapter 4
Chapter 4
Chapter 4
Control Statements: Part 1
Objectives
• Basic problem-solving techniques
• To develop algorithms through the process of top-down, stepwise refinement
• To use the if and if…else selection statements to choose among alternative
actions
• To use the while repetition statement to execute statements in a program
repeatedly
• Counter-controlled repetition and sentinel-controlled repetition
• To use the increment, decrement, and assignment operators
3
Introduction
• Before writing a program to solve a problem, we must have a thorough
understanding of the problem and a carefully planned approach to
solving it
• When writing a program, we must also understand the types of building
blocks that are available and employ proven program construction
techniques
4
Algorithms
• Any solvable computing problem can be solved by the execution a series
of actions in a specific order
• An algorithm is procedure for solving a problem in terms of
▫ the actions to execute, and
▫ the order in which the actions execute
• Specifying the order in which statements (actions) execute in a computer
program is called program control
• This chapter investigates program control using C++’s control statements
5
Pseudocode
• Pseudocode (or “fake” code) is an artificial and informal language that
helps to develop algorithms
• Similar to everyday English, convenient and user friendly
• Helps you “think out” a program before attempting to write it
• Carefully-prepared pseudocode can easily be converted to a
corresponding C++ program
• Normally describes only executable statements
• Declarations (that do not have initializers or do not involve constructor
calls) are not executable statements
6
Pseudocode
Below is an algorithm that inputs two integers from the user,
adds these integers and displays their sum
7
Control Structures
• Normally, statements in a program execute one after the other in the order in which
they’re written
▫ Called sequential execution
• Various C++ statements enable you to specify that the next statement to execute
may be other than the next one in sequence
▫ Called transfer of control
• All programs could be written in terms of only three control structures:
▫ the sequence structure
▫ the selection structure
▫ the repetition structure
• When we introduce C++’s implementations of control structures, we’ll refer to them
in the terminology of the C++ standard document as “control statements.”
8
Control Structures
• 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 Unified Modeling Language (UML) activity diagram in the figure
below illustrates a typical sequence structure in which two calculations
are performed in order
• C++ allows us to have as many actions as we want in a sequence
structure
9
10
Control Structures
• 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, such as the
sequence structure in the figure above
• 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
• Activity diagrams help to develop and represent algorithms, but many programmers
prefer pseudocode
• Activity diagrams clearly show how control structures operate
• Action states represent actions to perform
▫ Each contains an action expression that specifies a particular action to perform
11
Control Structures
• The arrows in the activity diagram are called transition arrows
• 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
Control Structures
• Rectangles with the upper-right corners folded over are called notes in
the UML
▫ Explanatory remarks that describe the purpose of symbols in the diagram
▫ Notes can be used in any UML diagram
• A dotted line connects each note with the element that the note
describes
13
Control Structures
• C++ provides three types of selection statements:
▫ The if selection statement either performs (selects) an action if a condition
(predicate) 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
14
Control Structures
• The if selection statement is a single-selection statement because it
selects or ignores a single action (or, a single group of actions)
• The if…else statement is called a double-selection statement because
it selects between two different actions (or groups of actions)
• The switch selection statement is called a multiple-selection statement
because it selects among many different actions (or groups of actions)
15
Control Structures
• 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 (or group of actions)
in their bodies zero or more times
• The do…while statement performs the action (or group of actions) in its
body at least once
16
Control Structures
• Each of the words if, else, switch, while, do and for is a C++
keyword
• These words are reserved by the C++ programming language to
implement various features, such as C++’s control statements
• Keywords cannot be used as identifiers, such as variable names
17
18
Control Structures
• Single-entry/single-exit control statements
▫ Control statements are attached to one another by connecting the exit point of one
to the entry point of the next
▫ Called control-statement stacking
▫ Only one other way to connect control statements—called control-statement
nesting, in which one control statement is contained inside another
19
20
if Selection Statement
• The following pseudocode determines whether “student’s grade is greater
than or equal to 60” is true or false
If student’s grade is greater than or equal to 60
Print “Passed”
Single-selection IF statement
22
if Selection Statement
• 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. For example the looping condition: while (true){ … }
• C++ provides the data type bool (Boolean) for variables that can hold only
the values true and false—each of these is a C++ keyword
23
▫ Closely related to the if…else statement, 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
▫ The third operand is the value for the entire conditional expression if the condition is false
• The values in a conditional expression also can be actions to execute
26
• If studentGrade is greater than or equal to 90, the first four conditions are true, but
only the output statement after the first if condition is executed, all others will be
skipped
28
• The two forms are identical except for the spacing and indentation, which the compiler
ignores
• The latter form is popular because it avoids deep indentation of the code to the right,
which can force lines to wrap
29
30
• Braces { } indicate that the second if statement is in the body of the first if and
that the else is associated with the first if
32
while (condition) {
Statements …
}
34
Counter-Controlled Repetition
• We use counter-controlled repetition to input the grades one at a time
▫ This technique uses a variable called a counter to control the number of times a
group of statements will execute (also known as the number of iterations of the
loop)
▫ Often called definite repetition because the number of repetitions is known before
the loop begins executing
38
Counter-Controlled Repetition
• A total is a variable used to accumulate the sum of several values
• A counter is a variable used to count—in this case, the grade counter
indicates which of the 10 grades is about to be entered by the user
• Variables that are used to store totals are normally initialized to zero
before being used in a program; otherwise, the sum would include the
previous value stored in the total’s memory location
39
40
41
42
static_cast operator
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
int x,y; float z;
int x,y; float z;
x=3;
x=3;
y=2;
y=2;
z= x/y;
z= static_cast <float> (x)/y;
cout<< z <<endl;
cout<< z <<endl;
return 0;
return 0;
}
}
output: 1
output: 1.5
45
Sentinel-Controlled Repetition
• Let’s generalize the class average problem
▫ Develop a class average program that processes grades for an arbitrary number of students
each time it’s run
• The program must process an arbitrary number of grades
▫ How can the program determine when to stop the input of grades?
• Can use a special value called a sentinel value (also called a signal value, a
dummy value or a flag value) to indicate “end of data entry.”
• Sentinel-controlled repetition is often called indefinite repetition
▫ the number of repetitions is not known in advance
• The sentinel value must not be an acceptable input value
50
#include <iostream>
int main()
{
cout << "Welcome to the grade book for\n" << "\n" << endl;
int total; // sum of grades entered by user
int gradeCounter; // number of grades entered
int grade; // grade value
double average; // number with decimal point for average
// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// prompt for input and read grade from user
cout << "Enter grade or -1 to quit: ";
cin >> grade; // input grade or sentinel value
51
Sentinel-Controlled Repetition
• Without the braces, the last three statements in the body of the loop would
fall outside the loop, causing the computer to interpret this code incorrectly,
as follows:
while ( grade != -1 )
{total = total + grade;} // add grade to total
• Good programming practice: use braces even if only one statement exists
inside the loop
54
Sentinel-Controlled Repetition
• The variable average is declared to be of type double to capture the fractional result
of our calculation
• total and gradeCounter are both int variables
• Recall that dividing two integers results in integer division, in which any fractional part of
the calculation is lost (i.e., truncated)
• In the following statement the division occurs first—the result’s fractional part is lost
before it’s assigned to average:
average = total / gradeCounter;
Compiler performs promotion (also called implicit conversion) on selected
operands
55
Sentinel-Controlled Repetition
• To perform a floating-point calculation with integers, create temporary
floating-point values.
• static_cast operator accomplishes this task
• The cast operator static_cast<double>(total) creates a
temporary floating-point copy of its operand in parentheses
▫ The value stored in total is still an integer
56
Sentinel-Controlled Repetition
• The call to setprecision in line 75 (with an argument of 2) indicates that
double values should be printed with two digits (could be rounded) of
precision to the right of the decimal point (e.g., 92.37)
▫ Parameterized stream manipulator (argument in parentheses)
▫ Programs that use these must include the header <iomanip>
• endl is a nonparameterized stream manipulator and does not require the
<iomanip> header file
• If the precision is not specified, floating-point values are normally output with
six digits of precision
57
Sentinel-Controlled Repetition
• Stream manipulator fixed indicates that floating-point values should
be output in fixed-point format, as opposed to scientific notation
• Fixed-point formatting is used to force a floating-point number to display
a specific number of digits
• Specifying fixed-point formatting also forces the decimal point and
trailing zeros to print, even if the value is a whole number amount, such
as 88.00
▫ Without the fixed-point formatting option, such a value prints in C++ as 88 without
the trailing zeros and decimal point
58
Sentinel-Controlled Repetition
• We could have also declared as unsigned int the variables grade,
total and average. Grades are normally values from 0 to 100, so the
total and average should each be greater than or equal to 0
• We declared those variables as int because we can’t control what the
user actually enters—the user could enter negative values
59
List Initialization
• C++11 introduces a new variable initialization syntax. List initialization (also called uniform
initialization) enables you to use one syntax to initialize a variable of any type
• or
List Initialization
• For fundamental-type variables, list-initialization syntax also prevents so-
called narrowing conversions that could result in data loss
• For example, previously you could write
int x = 12.7;
• which attempts to assign the double value 12.7 to the int variable x
• A double value is converted to an int, by truncating the floating-point
part (.7), which results in a loss of information—a narrowing conversion
67
Assignment Operators
• C++ provides several assignment operators for abbreviating assignment
expressions
• The += operator adds the value of the expression on the right of the
operator to the value of the variable on the left of the operator and
stores the result in the variable on the left of the operator
• Thus the assignment c += 3 adds 3 to c
68
69
Operator precedence
74
Exercise 4:
Display the following shape using a loop
#include<iostream>
using namespace std;
int main(void)
{
int counter=1;
while (counter <=7){
cout << "* \t\t *" << endl;
counter++;
}
}
78
int main(void)
{ Note:
double price = 2.45; (int) is similar to static_cast(int)
int dolar = (int)price;
int ct = (price-dolar) * 100;
cout<< ct <<" "<< dolar<<" "<< (dolar > 50 ? 'A' : 'B')<<endl;
}
The program extracts the fraction from
“price”, multiplies it by 100, then
compare it with 50
Output: 45 2 B
79