Download Chapter 3

Document related concepts
no text concepts found
Transcript
1
Chapter 3
Problem Solving and the Computer
 An algorithm is a step-by-step operations that the CPU must execute in order
to solve a problem, or to perform that task.
 A program is the specification of an algorithm in a programming language.
 Before you can write a program to solve a problem or to perform a task, you
must first determine an algorithm to solve that problem or to perform that task.
 This chapter discusses
 the basic operations that the CPU can perform, and
 how these operations are used to design algorithms.
2
Algorithm, Flowchart, and Pseudo-code

The basic operations of a C/C++ programming language are specified
using the following statements or structures:

the input statement

the output statement

the assignment statements

the single-way selection structure

the two-way selection structure

the multiple-way selection structure

the counter-controlled iteration structure, and

the logically-controlled iteration structure.
3
Pseudo-Code
 These statements and structures are specified in pseudo-code using English
language-like statements:
 The input statement may be specified using an English-like statement with
the keyword read into.
 The output statement may be specified using an English-like statement
with the keyword write.
 The assignment statement may be specified using an English-like statement
with the keyword compute or calculate.
4
Flowcharts
 They may also be specified using the flowchart symbols in Figure 3.2:

The input statement is specified by using symbol (b) in which the keyword
read is inserted along with the names of the variables where values should be
read.
The following says to read the first value into variable num1 and the second value
into variable num2:
Read
num1, num2

The output statement is specified by using symbol (b) in which the keyword
write is inserted along with the expressions whose values should be printed.
The following says to output the string constant “Result=” followed by the result
of the expression num * 5, followed by the result of the expression 3 * (num – 7):
Write
“Result =”, num * 5
3* (num – 7 )

The assignment statement is specified by using symbol (c) in which a C++
like assignment statement is inserted.
The following says to add the value in variable num1, to the value in variable
num2 and to store the result in variable sum:
sum = num1 + num2
5

The specification of each of the programming language structures
involves a test that the CPU must first performs on a logical
expression (also referred to as a condition).
6
Figure 3.1
Flowchart Symbols
7
SYMBOL
(a)
(b)
(c)
(d)
(e)
(f)
8
NAME
Terminal
Input/Output
Process
Flow Lines
Decision
Connector
9
DESCRIPTION
Indicates the beginning or the end of an algorithm.
Indicates an input or an output operation.
Indicates a computation or a data manipulation.
Used to connect the symbols and to indicate the logic flow.
Indicates a decision point in an algorithm.
Indicates an entry or an exit from another part of the flowchart.
10
Program Development
 There are six steps in the development of a program to perform a task or to
solve:
 These steps are organized into four phases:
 the requirements analysis phase
 the design phase
 the implementation phase and
 the testing phase
11
We use the following simple programming problem to discuss all these steps.
Given that the circumference of a circle is 2 *  * r, and that its area is  * r
* r, where r is its radius and  is the constant value 3.14, write a C++
program to read the radius of a circle, and to compute its perimeter and area.
12
Requirements Analysis Phase (Steps 1 and 2)
Step 1: you analyze the problem or the task in order to determine the desired
result(s) or the output items that the program must produce.
The objective our sample programming problem is:
to compute the circumference and the area of the circle.
The output items are therefore:
 the circumference of the circle
(identified as circumf )
 the area of the circle
(Identified as area)
Step 2: you analyze the problem or the task in order to determine the data
items (input or constants) that will be processed in order to produce
the desired result(s) or output items.
For our sample programming problem, the input item is:
the radius of the circle
(identified as radius).
13
Design Phase (Steps 3 and 4)
Step 3
1. You design an algorithm for transforming the data items (input or
generated) into the desired result(s) or output.
2. You specify the algorithm in one of the following ways:
 In a programming language,
 using a pseudo-code, or
 using a flowchart.
For our sample programming problem, the algorithm is specified in
pseudo-code as follows:
1. Read the radius of the circle into variable radius.
2. Calculate the circumference of the circle as follows:
circumf = 2 * 3.14 * radius
3. Calculate the area of the circle as follows:
area = 3.14 * radius * radius
4. Display the results (circumference and area).
14
 It is specified using a Flowchart as follows:
Variables:
radius
circumf
area
(double)
(double)
(double)
to hold the radius of the circle
to hold its circumference
to hold its area
Start
Read
radius
circumf = 2 * 3.14 * radius
area = 3.14 * radius * radius
Write
circumf, area
Stop
Step 4: You check the algorithm manually using specific data to make sure
that it is correct.
15
Implementation Phase (Step 5)
Step 5: You write the algorithm that you have designed in step 3 in a
programming language.
For our sample programming problem, the program is provided in
Figure 3.2
Testing Phase (Step 6)
Step 6: You test the program (using selected test data) to verify that it works
correctly, and that it also fulfills its requirements.
16
Figure 3.2
/*************************************************************
Program to read the radius of a circle and to compute its
circumference and area.
*************************************************************/
#include
<iostream >
using namespace std;
int main()
{
const double PI = 3.14; // holds the value of PI
double radius,
// to hold the radius of a circle
circumf,
// to hold its circumference
area;
// to hold its area
/*----------read the radius of the circle---------------*/
cout
<< “\nEnter the radius of the circle:\t”;
cin
>>
radius;
/*--------------compute its circumference---------------*/
circumf = 2 * PI * radius;
/*---------------compute its area ----------------------*/
area = PI * radius * radius;
/*-------------- print its circumference and area-------*/
cout
<<
endl << “The circumference of the circle is:\t”
<< circumf << endl << “and its area is:\t” << area;
return( 0 );
}
17
Exercise 3.1
1.a.
Specify an algorithm (in pseudo-code and using a flowchart) to read the
width and the length of a rectangle and to calculate its perimeter and area.
1.b.
Write the C++ program that corresponds to the algorithm in question 1a.
The output of your program must look like the following:
Enter the width of the rectangle (in inches): 12.5
Enter its length (in inches) : 10.0
Its perimeter is: 45.0 inches
Its area is:
125.0 square inches
2. In the division of a positive integer value by 10, the quotient is the same
number without the right-most digit (for example, 345 / 10 = 34), and the
remainder is the right-most digit (for example, 345 % 10 = 5).
a. Specify an algorithm (using a flowchart) to read a 3-digit positive integer
value, and to output its digits in reverse order (for example, if the integer
value is 345, the output will be 5 4 3).
b. Write the C++ program that corresponds to the algorithm in question 2a.
The output of your program must look like the following:
Enter a three-digit integer value:
The digits of this number are:
345
5 4 3
18
3.3 Logical Expressions

A logical expression (or condition) is an expression that evaluates to
either true or false.

There are two types of conditions:

simple conditions and

Compound conditions.
19
Simple Conditions

A simple condition has the following syntax:
<arithmetic expression> <relational operator> <arithmetic expression>
Relational Operators
C/C++ Symbol
Meaning
<
is less than
>
is greater than
==
is equal to
<=
is less than or equal to
>=
is greater than or equal to
!=
is not equal to
20
Evaluation of simple conditions
 Assuming that the variables are defined and initialized as follows:
int num1 = 5 , num2 = 7 , num3 = 2;
float fnum = 11.75;
char ch = ‘K’;
Solutions
a) num1 >= 5
5
d) num2 + 3 == num3 * 4
>= 5
7 + 3 == 2 * 4
True
10 ==
8
False
b) fnum + 7.2 != fnum / 2
11.75 + 7.2 != 11.75 / 2
18.95
!=
e) 3 * num1 + 4 < num3 * 2
3*5+4 < 2*2
5.875
19
True
False
c) fnum * 2 > num1 +20
f) ‘A’ <= ch
11.75 *2 > 5 + 20
‘A’ <=
23.5
>
25
False
< 4
True
‘K’
21
 Characters are ordered according to their ASCII code representations:
‘0' < ‘1' < ‘2' < . . . < ‘9' < ‘A’ < . . . < ‘Z’ < ‘a’ . . . < ‘z’.
Exercise 3.2
Assuming that the variables are defined and initialized as follows:
int num1 = 9 , num2 = 5 , num3 = 10;
float fnum = 12.50;
char ch = ‘P’;
Evaluate the following conditions:
a. num1 <= 5
b. 3 * num1 + 4 < num3 * 2
c. 3 * num2 > fnum + 2
d. 2 * num1 + 12 == 3 * num3
e. num1 + 3 != num1 * 4
f. ch – ‘M’ == 5
22
 Relational operators have a lower precedence than arithmetic operators:
 In the absence of parentheses, arithmetic operations are evaluated before any
relational operation is evaluated.
 However, it is a good programming practice to use parentheses to clarify the
meaning of logical expressions.
Example:
(fnum * 2) > (num1 + 20)
23
Compound Conditions
 A compound condition is built from simple conditions and logical operators.
Logical Operators
C++ Symbol
&&
Meaning
AND
||
OR
!
NOT
Evaluation
<condition1> && <condition2> is true if
and only if both conditions are true
<condition1> || <condition2> is true if and
only if at least one of the two conditions is
true
!<condition> is true if and only if
<condition> is false
24
Evaluations of compound conditions
True || True
True || False
True
True && True
False || Tue
True
True
True && False
True
False || False
False
False && True
False
False && False
False
False
short-circuit evaluation
 There is a short-circuit evaluation of a compound condition when you do not
have to evaluate the right-most condition to get its true value:
True || True
and
True || False
Therefore
True
|| True
False && True
True
and
False && False
True
Therefore
False
&& False
False
False
25
 Assuming that the variables are defined and initialized as follows:
int num1 = 5, num2 = 7, num3 = 2;
float fnum = 11.75;
char ch = ‘K’;
 Compute the true value of each of the following compound conditions:
a) num1 >= 5 || num2 + 3 == num3
d) num2 + 3 == num3 * 4 || ch >=
‘Z’
b) ‘A’ <= ch
&& fnum + 7.2 != 2.5
e) num1 < 3 && num2 > num3
c) !(3 * num1 + 4 < num3 * 2)
f) !(fnum * 2 < num1 + 20)
Solutions
a) num1 >= 5 || num2 + 3 == num3
5
d) num2 + 3 == num3 * 4 || ch >= ‘Z’
>= 5 ||
7 + 3 == 2 * 4
True
10 == 8
True
False
|| ‘K’ >= ‘Z’
|| False
|| False
False
b) ‘A’ <= ch
&& fnum + 7.2 != 2.5
num3
‘A’ <= ‘K’ && 11.75 + 7.2 != 2.5
True &&
18.95
True &&
True
True
!= 2.5
e) num1 < 3 && num2 >
5 < 3 &&
False
False
26
27
c) !(3 * num1 + 4 < num3 * 2)
!( 3 * 5 + 4
< 2 * 2)
f) !(fnum * 2 < num1 + 20)
!(11.75 * 2 < 5 + 20)
!( 19 < 4)
!( 23.50
! False
!True
True
False
< 25)
28
Precedence of C/C++ Operators
 The following table lists C/C++ arithmetic, relational, and logical operators
with their relative order of precedence.
 In the evaluation of an expression, operators with higher precedence are
evaluated before those with lower precedence.
 Operators with the same precedence are evaluated in the order specified in the
“order of evaluation” column.
29
Operator Order of Evaluation Precedence
!
Unary –
right to left
7
left to right
6
left to right
5
left to right
4
==
!=
left to right
3
&&
left to right
2
||
left to right
1
*
/
%
+
<
<=
>
>=
Accuracy of Floating-Point Values
 The fact that floating-point values are approximated inside a computer makes it
difficult to test for the equality of floating-point values.
For example, if the variable fnum is defined as follows:
float fnum = 7.1;
30
Then, the condition:
fnum / 2 == 3.55
may not be true.
 The problem may be solved by assuming that two floating-point values are
equal if their difference is relatively very small.
 This is done by testing if the absolute value of their difference is less than a
certain value chosen by the programmer (for example 0.000001).
 Using the library function fabs() that takes as argument a floating-point value
and returns its absolute value, the condition:
value1 == value2
is replaced with the condition:
fabs(value1 - value2) < 0.000001
which tests whether the difference between the two values is small enough so
that we can make them equal.
31
Evaluation of True and False
 In the C/C++ programming language,
 The integer value 0 represents false
 Any value other than 0 represents true.
 The following conditions are therefore equivalent (you can replace one with the
other):
Conditions
value != 0
and
value
Saying that value is not zero is the same thing as saying that value is true
Conditions
value == 0
and
! value
Saying that value is zero is the same thing as saying that
value is false
or
!value is true
32
bool Data Type
 A variable with data type bool can only hold the bool values true and false.
Examples:
bool flag = true;
bool condValue = false, HighTemperature, ExtremeTemperature;
double temperature;
HighTemperature = false;
cin
>> temperature;
HighTemperature = (temperature >= 120);
ExtremeTemperature = (HighTemperature || (temperature <= -20);
33
Exercise 3.3
A. Assuming that the variables are defined and initialized as follows:
int num1 = 9 , num2 = 5 , num3 = 10;
float fnum = 12.50;
char ch = ‘P’;
Evaluate the following conditions (using short circuit evaluation whenever
possible):
a. 2 * num1 - 5 >= 9 || fnum / 2 + 10 <= 6.5
b. num1 + num2 == num3 + 5 && 2 * num3 <= 4 * num2
c. ! (num1 + 5 <= 13)
d. 3 * num1 > num1 + num2 && num1+ 3 >= 12
e. ! ( num3 % 4 < 3)
f. num1 - 5 >= num3 || num2 < 15 && num1 >= 9
B. Which of the following conditions are equivalent (that means have the same true
value)?
a. num1 != 0
b. !num1
c. num1 == 0
d. !(num1 == 0)
e. num1
C. Suppose that a person’s age is stored in the variable age, his number of children in
the variable NumChild, his salary in the variable salary, and his height in the
variable height. Write relational expressions to specify the following conditions:
a. he is 45 year old.
b. he is more than 5.7 feet tall.
c. his salary is between 35,000 and 50,000.
d. he does not have 3 children.
h. he is either 6.0 feet tall, or he has less than 4 children.
j. he is not older that 35 and he has 2 or 3 children
34
35
3.4 Two-Way Selection using the if-else Structure
Purpose
To ask the CPU to test a condition and then to choose the course of action(s)
to perform based on whether that condition is true or false.
36
 A two-way selection structure is specified using a flowchart as follows:
False
Condition
True
T-Statement
F-Statement
Next-Statement
 It says to do the following:
Test condition
a. if it is true, perform the operations specified by T-Statement
b. otherwise, perform the operations specified by F-Statement.
 T-Statement is one or more statements that specify the T-Action,
 F-Statement is one or more statements that specify the F-Action
 Next-Statement is the statement that specifies the action to be performed next.
37
38
 It may be specified in pseudo-code as follows:
1. If <condition> is true, do the following:
<T-Statement>
2. Otherwise, do the following:
<F-Statement>
3. <Next-Statement>
39
 It is specified in the C++ programming language using the if - else structure with
the following syntax:
if(<condition>)
<T-statement>
else
<F-statement>
<Next-Statement>
Here:
 <T-statement> is a single statement that specifies the T-Action
 <F-statement> is a single statement that specifies the <F-Action>.
40
Case Study 3.1
Problem Statement
Write a program to read the age of an individual, and to output the message
“serve alcohol drink” if he is 21 or older, and the message “serve juice”
otherwise. Your program will then output the message “thank you for using
this program.”
41
42
Program Logic
output:
“Serve alcohol” or “Serve Juice”, depending on the individual’s age.
Input:
an individual’s age.
Variables:
age
(int) to hold an individual’s age.
Algorithm Specification (using a Flowchart)
start
Read
age
False
True
age > =21
Write
“Serve Juice”
Write
“Serve alcohol drink”
Write
“Thank you for
Using this program”
Stop
43
44
45
46
47
Algorithm Specification (using Pseudo-code)
1. Read the individual’s age into variable age.
2. If this individual’s age is 21 or more, do the following:
2.a.
output the message “serve alcohol drink”.
3. Otherwise, do the following:
3.a.
output the message “serve juice”.
4. Output the message “thank you for using this program”.
48
Figure 3.3
Using the if-else Structure
/***************************************************************
Program to read the age of an individual and to output the
type of drink that he should be served
***************************************************************/
#include
<iostream>
using namespace std;
#define DRINKAGE
int main()
{
int age;
21
// to hold an individual’s age
/*----------- read the individual’s age--------------------*/
cout << “\n\nEnter the individual’s age please:\t”;
cin
>> age;
/*---determine what type of drink he should be served -----*/
if (age >= DRINKAGE)
// he is over the drinking age
cout << endl << “Serve alcohol drink”;
else
// he can not drink alcohol
cout << endl << “Serve juice”;
cout << endl << “Thank you for using this program”;
return (0);
}
49
Practice
Exercise 3.4 (1 a and b).
Homework Exercise 3.4 (2 a and b).
Exercise 3.4
1.a.
Specify an algorithm (in pseudo-code and using a flowchart) to read a
non-zero integer value and to determine if it is positive or negative. If it is
positive, print it with the message “POSITIVE”, otherwise, print it with the
message “NEGATIVE.” At the end, print the message “Thank You.”
1.b.
Write the C++ code segment that corresponds to the algorithm in question 1a.
2.a.
Specify an algorithm (using a flowchart) to read a character value and to
determine if it is a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). If it is, print it with the message
“DIGIT”; otherwise print it with the message “NOT A DIGIT.”
2.b.
Write the C++ code segment that corresponds to the algorithm in question 2a.
50
Case Study 3.2
Problem Statement
Write a program to read a positive integer value and to determine if it is even or
odd. If it is even, print it with the message “EVEN”; otherwise, print it with the
message “ODD”.
Program Logic
Output:
the input value with the message “EVEN” or “ODD”, depending
on whether the input value is even or odd.
Input:
an integer value.
Variable:
num (int) to hold the input value.
Note:
An integer value is even if the remainder in its division by 2 is 0; otherwise, it is
odd.
51
Algorithm Specification (using Pseudo-code)
1. Read a positive integer value into the variable num.
2. If num % 2 is 0, then do the following:
2.a
print the input value with the message “EVEN”.
3. Otherwise do the following:
3.a
print the input value with the message “ODD”
52
Algorithm Specification (using a Flowchart)
Start
Read
num
False
num % 2 = 0
True
Write
num, “even”
Write
num, “odd”
Stop
53
54
Figure 3.4
Using the if - else Structure
/**************************************************************
Program to read an integer value and to determine if it is
even or odd
**************************************************************/
#include
<iostream>
using namespace std;
int main()
{
int num;
// to hold the value read
/*---------------- read in an integer value---------------*/
cout << “\n\nEnter an integer value please:\t”;
cin >> num;
/*----------------determine if it is even or odd ---------*/
if (num % 2 == 0)
cout <<
endl <<
else
cout <<
num
endl << num
return ( 0 );
}
// it is even
<< “\tEVEN”;
// it is odd
<< “\tODD”;
55
Practice Exercise 3.5.
Exercise 3.5
1.a.
Specify an algorithm (using a flowchart) to read an integer value and to
determine if it is a multiple of 5. If it is a multiple of 5, print it with the message
“MULTIPLE OF 5”, otherwise, print it with the message NOT MULTIPLE OF 5.”
1.b.
1a.
Write the C++ code segment that corresponds to the algorithm in question
56
Compound Statement
 A compound statement has the following syntax:
{
(One or more statements to be executed as a block)
}
Example
{
cout << “\n\nEnter the dividend please:\t”;
cin >> dividend;
cout << “\nThe quotient in the division of:\t”
<< dividend << “ by ” << divisor << “\tis:\t”
<< (dividend / divisor);
cout << “\nand the remainder is:\t” << (dividend % divisor);
}
 The statements of a compound statement are executed one after another,
starting with the first one in the sequence.
Purpose
To specify two or more statements where only one statement is allowed.
57
Examples
if(num1 > num2)
{
num2 = num1 + 5;
num1 = num1 +1;
}
else
num1 = num2 -5 ;
if(num1 < num2)
num2 = num1 + 4;
else
{
num2 = num1 + 5;
num1 = num1 +1;
}
58
59
Case study 3.3
Problem Statement
Write a program to read an integer value and to do the following:
 If the value read is zero, print it with the message “INVALID DIVISOR”.
 Otherwise read a second value and then compute and print the quotient and the
remainder in the division of the second value by the first.
 At the end write the message “Thank you for using this program.”
Program Logic
Output:
If the first input value is zero, output message “0 is invalid divisor”
Otherwise, output the quotient and the remainder in the division of the
second value by the first.
Input:
one or two integer values, depending on the value of the first.
Variables:
divisor
(int)
to hold the first value.
dividend
(int)
to hold the second value.
Note:
The second value is input and the quotient and the remainder in the division
of the second value by the first are computed only if the first value is not
zero.
60
Algorithm Specification (using a Flowchart)
Start
Read
divisor
False
divisor == 0
True
Write
divisor
“invalid divisor”
Read
dividend
Write
dividend / divisor
dividend % divisor
Write
“Thank you”
Stop
61
Algorithm Specification (using Pseudo-Code)
1. Read the first value into variable divisor.
2. If the value read is zero (divisor == 0), do the following;
2.a
write the value read (0) with the message “INVALID DIVISOR”
3. Otherwise do the following:
3.a
read the second value into variable dividend.
3.b
write the quotient of second value divided by the first:
dividend / divisor
3.c
write the remainder of the second value divided by the first:
dividend % divisor
4. Write the message “Thank you for using this program”.
62
Figure 3.5
Using a Compound Statement in an if-else Structure
/***************************************************************
Program to read two integer values and to compute the quotient
and the remainder in the division of the second value by the
first.
***************************************************************/
#include
<iostream>
using namespace std;
int main()
{
int divisor,
dividend;
// to hold the first value
// to hold the second value
/*---------------- read in the divisor--------------------*/
cout << “\n\nEnter the divisor please:\t”;
cin >> divisor;
if (divisor == 0)
// it is invalid
cout << endl << divisor << “\tIS INVALID DIVISOR”;
else
{
/*read the dividend and compute the quotient and remainder*/
cout << “\n\nEnter the dividend please:\t”;
cin >> dividend;
cout << “\nThe quotient in the division of:\t”
<< dividend << “ by ” << divisor << “\tis:\t”
<< (dividend / divisor);
cout << “\nand the remainder is:\t” << (dividend % divisor);
}
cout << “\n\nThank you for using this program”;
return( 0 );
}
63
Practice
Exercise 3.6 (2 and 3).
Homework
Exercise 3.6 (1).
Exercise 3.6
1. Assuming that all variables are properly defined and initialized, what are the
error(s) in each of the following program segments:
a. cin >> num;
if (num = 5)
sum = num + 4;
else
sum = num + 10;
b. cin >> num;
if (num > 5 && <= 10)
cout << (num + 15);
else
cout << (num - 3);
c. cin >> num;
if (num < 15)
result1 = 2 * num;
result2 = num + 20;
else
result1 = 5 * num;
result = result1 + result2;
cout << “\nThe result is:\t” << result;
64
2. Trace the execution of the following program segment and show its output for each
of the following input values:
a. input: 4
Line #
1
2
3
4
5
6
b. input: 20
Statements
cin >> num;
if (num <10 )
{
num = num + 6;
cout << endl << “num =\t” << num;
}
else
cout << endl << “num / 4 =\t” << (num / 4);
cout << endl << “result =\t” << (2 * num);
3a. Specify an algorithm (using a flowchart) to read an integer value into
variable num and to do the following: if the value read is greater than 10, subtract 2
from it (replace the old value of variable num with the result), and print the result;
otherwise, add 3 to it (replace the old value of variable num with the result) and
print the result. Finally, multiply the new value of variable num by 5, and print the
result.
3b.
3a.
Write the C++ code segment that corresponds to the algorithm in question
65
3.5 Counter-Controlled Iteration using the while
Structure
Purpose:
To ask the CPU to repeat the execution of one or more actions a set number of
times.
Example:
Suppose that a candy bar costs 70 cents in a candy machine that only accepts
dimes. To buy a candy bar from this machine, a user has to deposit a dime in the
machine seven times.
 The operations that are repeated are usually referred to as the body-of- the- loop.
66
The loop counter:
 Is needed to count the number of times that the operations have already been
executed (or about to be executed).
 initial value: 0 (no execution is done yet) - final value: the number of
executions
 initial value 1 (one execution is about to be done) – final value: number of
execution plus 1.
Loop Increment
 After each execution of the body-of-the-loop, the loop counter must be updated
to reflect the number of executions.
 The statement that you use to update the loop counter is called the loop
increment.

The loop increment is a statement in the body-of-the-loop.
67
 This structure is specified using a flowchart as follows:
counter = initial-value
False
Counter < final-value
True
Body-of-the-Loop
Next-Statement
Body-of- the- Loop
counter
consists of the statements whose executions are repeated
by the CPU.
is the loop counter
it is a variable that is used to hold the number of repetitions
Next-Statement
is the first statement to be executed after the repetitions.
 It may be specified using pseudo-code as follows:
1. Set the loop-counter to the initial-value.
2. As long as the loop-counter is less than the final-value, do the
following:
<Body-of-of the-loop (including the increment-statement)>
3. Execute the next operation.
68
 It is specified in the C/C++ programming language using the while structure as
follows:
counter = initial-value;
while (counter < final-value)
{
<Body-of-of the-loop (including the increment-statement)>
}
<Next-statement>
69
Algorithm of the Candy Bar Machine (using a flowchart)
Start
total = 0
count = 0
False
True
count < 7
Read
coin
total = total + coin
count = count + 1
Write
“Thank you”
Stop
70
Algorithm of the Candy Bar Machine (in pseudo-code)
1. Set the total value of the coins to 0:
total = 0.
2. Set the loop counter to 0: count = 0.
3. As long as the loop counter is less than 7, do the following:
3.a.
read the value of the coin into the variable coin.
3.b. add the value of the coin read into the total value: total = total +
coin.
3.c.
increment the loop counter by 1: count = count + 1.
4. Write “Thank You”
Algorithm of the Candy Bar Machine (in C++)
int total,
coin,
count;
// to hold the total value of the coins
// to hold the value of a coin
// to hold the number of repetitions
total = 0;
count = 0;
while ( count < 7 )
{
cin >> coin;
total = total + coin;
count = count + 1;
}
cout << endl << “Thank You”;
71
Case Study 3.4
Problem Statement
Write a program to read 30 weight measurements in pounds and to convert
them into kilograms. Note that 1 Lb = .454 Kgs.
Program Logic
Input:
30 weight measurements (in Lb).
Output:
30 weight measurements (in Kg).
Notes:
 We use the variable count as the loop counter:
Its initial value is 0 (no weight measurement is read so far) and
Its final value is 30 (30 weight measurements are already read)
Variables:
count (int)
to count the weight measurements.
Initial value is 0 - Final value is 30.
pound (double)
to hold a weight measurement in Lbs.
72
Algorithm Specification (using Pseudo-code)
1. Set the loop counter (count) to 0: count = 0
3. As long as the current value of the loop counter (count) is less than
30, do the following:
3.a
read a weight measurement into the variable pound.
3.b
convert it to kilogram and print the result.
3.c
increment the loop counter by 1:
4. Write “Thank you”.
count = count + 1
73
Algorithm Specification (using a flowchart)
Start
count = 0
False
True
count < 30
Read
pound
Write
.454 * pound
count = count + 1
Write
“Thank you”
Stop
74
75
Figure 3.6 Counter-Controlled Iteration using the while Structure
Line Number
1 /**********************************************************
2
Program to read 30 weight measurements in pounds and convert
3
them into kilograms
4 **********************************************************/
5 #include
<iostream>
6 #include
<iomanip>
7 using namespace std;
8
9 #define
MAXCOUNT 30
10 #define
COEFICIENT .454
11
12 int main()
13 {
14
int count;
// to count weight measurements
15
double pound, // the current weight measurement in Lbs
16
17
cout << setprecision(2) << fixed
<< showpoint;
18
19
/*read weight measurements (Lb) and convert them to kg*/
20
count = 0;
// no weight measurement is read so far
21
while (count < MAXCOUNT)
// repeat thirty times
22
{
23
cout
<<
“\nEnter a weight measurement please:\t”;
24
cin
>>
pound;
25
cout << “\t = ” << (.454 * pound);
26
count = count + 1;
27
}
28
29
cout << endl << “Thank you”;
30
return (0);
31 }
 The body of the loop consists of the statements in line 23 to line 26.
 The loop-counter is initialized in line 20; and the loop-increment statement is in line
26.
76
Practice:
Exercise 3.7 (1 ).
Homework: Exercise 3.7 (2).
Homework Exercise 3.7
1. Assuming that all variables are properly defined, indicate what is wrong with each of
the following while structures:
a.
b.
while( count < 10 )
{
cin >> num;
cout << 2 * num;
count = count + 1;
}
2.a.
c.
while(count < 10)
{
count = 0;
cin >> num;
cout << 2 * num;
count = count + 1;
}
count = 0;
while(count < 10 )
{
cin >> num;
cout << 2 * num;
}
Specify an algorithm (in pseudo-code and using a flowchart) to read 50
temperature values in Fahrenheit and to convert them to Celsius. You convert a
Fahrenheit temperature to Celsius by using the following formula:
Celsius = 5.0 / 9 (Fahrenheit - 32).
2.b.
Write the C++ code segment that corresponds to the algorithm in question 2a.
77
Using a Running Total
 A running total is a variable that is used to compute the sum of values processed at
each iteration of a loop: it is first initialized to 0 and each new value processed in the
loop is added to the previous total.
Case Study 3.5
Problem Statement
Write a program to read 20 integer values and to compute their sum.
Program Logic
Input:
Output:
20 integer values.
their sum.
Variable:
count (int)
to count the values.
Initial value is 0 (no value is read so far); Final value is 20.
value
(int)
to hold the integer value read.
totalValue (int) to hold the sum of the integer values read so far: Initial
value is 0.
78
79
Algorithm Specification (using Pseudo-code)
1. Set the running total value (totalValue) to 0: totalValue = 0
2. Set the loop counter (count) to 0:
count = 0
3. As long as the current value of the loop counter (count) is less than 20, do the
following:
3.a
read an integer value into the variable value.
3.b
add the integer value read to the running total value:
totalValue = totalValue + value
3.c
add 1 to the loop counter (count):
4. Print the sum of all values
count = count + 1
80
Algorithm Specification (using a Flowchart)
Start
totalValue = 0
count = 0
False
count < 20
True
Read
value
totalValue = totalValue + value
count = count + 1
Write
totalValue
Stop
81
Figure 3.7
Line Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Counter-Controlled Iteration using the while Structure
/*************************************************************
Program to read twenty integer values and to compute their sum.
*************************************************************/
#include
<iostream>
using namespace std;
#define
MAXCOUNT
20
int main()
{
int count;
value,
totalValue;
// to count values
// to hold the value read
// the hold the sum of the values read so far
/*------read all values and compute their sum-------*/
totalValue = 0;
count = 0;
// no value has been read so far
while (count < MAXCOUNT)
// repeat twenty times
{
cout
<<
“\nEnter an integer value please:\t”;
cin
>>
value;
totalValue = totalValue + value;
count = count + 1;
}
/*-----print the sum of all the values read----------*/
cout <<
“\n\nThe sum of all the values read is:\t”
<<
totalValue;
return (0);
}
82
Exercise 3.8
1. The following two code segments are written to read and compute the sum of 10
integer values. Assuming that all variables are properly defined, indicate what is
wrong with each of them.
a.
b.
count = 0;
count = 0;
while (count < 10 )
while (count < 10 )
{
{
sum = 0;
cin >>
cin >> num;
num;
sum = sum + num;
sum = sum + num;
count = count + 1;
count = count + 1;
}
}
2.a.
Specify an algorithm (using a flowchart) to read the test scores of twenty students
and to compute and print their average.
2.b.
Write a C++ code segment that corresponds to the algorithm in 2.a
83
Case Study 3.6
Problem Statement
Write a program to compute the sum of the first 20 positive even integer values (2,
4, . . .).
Program Logic
Input:
Output:
none.
the sum of the first 20 positive integer values.
Variable:
count (int)
to count the values:
Initial value is 1; Final value is 21.
totalValue (int) to hold the sum of the integer values processed so far: Initial
value is 0.
Algorithm Specification (using Pseudo-code)
1. Set the running total value (totalValue) to 0: totalValue = 0
2. Set the loop counter (count) to 1:
count = 1
3. As long as the current value of the loop counter (count) is less than 21, do the
following:
3.a
multiply the loop counter by 2 and add the result to the running total value:
totalValue = totalValue + 2 * count
3.c
add 1 to the loop counter (count):
4. Print the sum of all values
count = count + 1
84
Algorithm Specification (using a Flowchart)
Start
totalValue = 0
count = 1
False
count < 21
True
totalValue = totalValue + 2 * count
Write
totalValue
count = count + 1
Stop
85
Figure 3.8
Counter-Controlled Iteration using the while Structure
Line Number
1
/*********************************************************
2
Program to read twenty integer values and to compute their
sum.
3
**********************************************************/
4
#include
<iostream>
5
using namespace std;
6
#define
MAXCOUNT 21
7
8
int main()
9
{
10
int count,
// to count the values
11
totalValue; // the hold the sum of the values so far
12
13
totalValue = 0;
14
count = 1;
15
while (count < MAXCOUNT)
// repeat twenty times
16
{
17
totalValue = totalValue + 2 * count;
18
count = count + 1;
19
}
20
22
/*-print the sum of the first 20 positive even values */
23
cout <<
“\n\nThe sum of the first 20 positive even
values is:\t”
24
<<
totalValue;
25
return (0);
26
}
86
Exercise 3.9
1.a.
Specify an algorithm (using a flowchart) to compute and print the sum of the first
10 positive multiple of 5.
1.b.
Write a C++ code segment that corresponds to the algorithm in 1.a.
87
Using a Running Product and a Counter with the initial value Greater
than the final Value
 A running product is a variable that is used to compute the product of values
processed at each iteration of a loop: it is first initialized to 1 and each new value
processed in the loop is multiplied to it.
Case Study 3.7
Problem Statement
For a positive integer value n, n factorial (written n!) is the product of all the
integer values from 1 to n (1 * 2 * 3 * . . . * n).
Write a program to read a positive integer value n, and to compute and print n!
Program Logic
Input:
a positive integer value.
Output: the product of all positive integer values less than or equal to the value
read.
Variables:
number (int)
to hold the value read
factorial (int)
to hold the product of the integer values: initial value = 1
88
After
Iteration
Value of number
value of factorial
-
n
1
1
n-1
1xn
2
n-2
1 x n x (n - 1)
.
.
.
n-1
1
1 x n x (n - 1) x . . . x 2
Algorithm Specification (in Pseudo-code)
1. Read a positive integer value into variable number.
2. Initialize the variable factorial to 1: factorial = 1
3. As long as the current value of variable number is greater than 1, do the
following:
3.a
multiply the current value of variable factorial by the current value of
variable number:
3.b
factorial = factorial * number
subtract 1 from the current value of variable number: number = number-
4. Print the result.
89
Algorithm Specification (using a Flowchart)
Start
Read
number
factorial = 1
False
number > 1
True
Factorial = factorial * number
number = number - 1
Write
factorial
Stop
90
91
92
Figure 3.9
Counter-Controlled Iteration using the while Structure
Line Number
1
/*****************************************************
2
Program to read a positive integer value and to
compute and print its factorial.
3
****************************************************/
4
#include
<iostream>
5
using namespace std;
6
int main()
7
{
8
int number,
//integer value/loop counter
9
factorial = 1;
// to hold the product
10
11
/*-----read the integer value --------------------*/
12
cout << endl << “enter a positive integer value:\t”;
13
cin
>> number;
14
15
/*--compute the factorial of the number read ----*/
16
while (number > 1)
17
{
18
factorial = factorial * number;
19
number = number -1;
20
}
21
22
/*------print the factorial------------------*/
23
cout <<
endl
<<
“n factorial is:\t”
24
<<
factorial;
25
return (0);
26
}
 The body of the loop consists of the statements in lines 18 and 19.
 The loop-counter is initialized in line 13; and the loop-increment statement
is in line 19.
93
Exercise 3.10
1.a.
Specify an algorithm (using a flowchart) to read ten integer values, to
compute their product and to output the result.
1.b.
Write the C++ code segment that corresponds to the algorithm in 1.a.
2a.
Specify an algorithm (using a flowchart) to generate the squares (n*n) of the
integer values 20, 18, 16, 14, . . . , 2, starting with 20.
2.b.
2.a.
Write the C++ code segment that corresponds to the algorithm in question
94
3.6 Logically-Controlled Iteration using the while
Structure
Purpose
To repeat the execution of one or more statements as long as a certain condition
is true.
Case Study 3.7
Problem Statement
A can of soda costs $ 1.00 in a soda machine, and a user buys a can of
soda by depositing coins (nickels, dimes or quarters) in the machine until the
total value of the coins deposited in the machine is greater than or equal to $
1.00.
Write a program to read the value of each coin deposited in the soda
machine (5, 10, or 25) until the total value of the coins deposited in the
machine is greater than or equal to 100. The program will then output the
message “Thank you for using the soda machine” and the amount of the
change.
95
Program Logic
input:
the value of a coin (5, 10 or 25).
Output: the message “Thank you for using this soda machine” and the amount
of change.
Note:
 To read the value of each coin deposited in the machine and to compute their
sum, we need the following:
 A variable coinValue to hold the input value of a coin.
 A variable totalValue to hold the sum of the coins values input sofar.
It is initialized to 0 before the body-of-the-loop.
 The loop condition is therefore: totalValue < 100.
96
© 2010 Gilbert Ndjatou
Page 97
98
Variables:
coinValue ( int )
to hold the value of a coin.
totalValue ( int )
to hold the total value of the coins deposited so far.
Algorithm Specification (using Pseudo-code)
1. Set the total value of the coins (totalValue) to 0.
2. As long as variable totalValue is less than 100 do the following:
2.a
read the next coin value into the variable coinValue.
2.b
add the coin value read to the total value of the coins:
totalValue = totalValue + coinValue
3. Output the message “Thank you for using the soda machine”.
4. Compute and print the change:
totalValue - 100
99
100
Algorithm Specification (using a Flowchart)
Start
totalValue = 0
False
True
totalValue < 100
Read
coinValue
totalValue = totalValue + coinValue
Write
“Thank you”
Write
totalValue - 100
Stop
101
102
Figure 3.10
Logically-Controlled Iteration using the while Structure
Line Number
1
/********************************************************
2
Program to monitor the purchase of a can of soda in a
soda machine
3
********************************************************/
4
#include
<iostream>
5
using namespace std;
6
int main()
7
{
8
const int SODAPRICE = 100;//the price of a can of soda
9
int coinValue,
// the value of a coin
10
totalValue = 0;
// the total value of the coins
11
12
13
14
while( totalValue < SODAPRICE )
{
/*------read the value of the next coin---------*/
cout << endl << “enter the value of the next
coin:\t”;
cin
>> coinValue;
15
16
17
18
19
20
21
22
23
24
25
/* compute the total value of the coins so far*/
totalValue = totalValue + coinValue;
}
/*-say “thank you” and give the change back */
cout << “\n\nThank you for using this soda machine”
<< “\n\nYour change is:\t”
<< (totalValue - SODAPRICE);
return ( 0 );
}
 The body-of-the-loop consists of the statements in lines 14 to 18.
 The loop-initialization statement is the declaration statement in line 10; and
 the loop-increment statement is in line 18.
103
Exercise 3.11
The manager of a store is required to make a deposit of $ 10,000 whenever the
total sales in the store is $ 10,000 or more.
a. Specify an algorithm (using a flowchart) to repeatedly read the daily sales in
that store, and to compute their sum until the total sales is greater than or equal
to $ 10,000. The total sales, the message “it is time to make a deposit” and the
remaining balance are then printed.
b. Write the C++ code segment that corresponds to the algorithm in question a.
104
105
Case Study 3.7
Problem Statement
Write a program to read a positive integer value and to print its digits in reverse
order. That means, 4321 is printed as 1 2 3 4, and
97 is printed as 7 9.
Program Logic
Input:
a positive integer value.
Output:
the digits of this integer value in reverse order.
Notes:
 In order to read a positive integer value and to write its digits in reverse
order, we need a variable num to hold the integer value.
 Its digits are printed in reverse order as follows:
 We divide the value of variable num by 10:
The remainder is the left-most digit of this value.
 We divide the value of variable num again by 10:
The quotient is this value without its left-most digit.
Example:
345 % 10 = 5
345 / 10 = 34
 We now replace the current value of variable num with the above quotient
 All the digits of the number will be printed if we repeat the above three
operations until the current value of variable num becomes 0.
106
Variables:
num ( int )
to hold the positive integer value and the successive quotients
in the division by 10.
Algorithm Specification (using Pseudo-Code)
1. Read the integer value into variable num.
2. As long as the value in variable num is not 0, do the following:
2.a
write num % 10.
2.b
set num to num / 10.
107
Algorithm Specification (using a Flowchart)
Start
Read
num
False
num != 0
True
Write
num % 10
num = num / 10
Stop
108
109
Figure 3.11
Logically-Controlled Iteration using the while Structure
Line Number
1 /********************************************************
2 Program to read a positive integer value and to print its
digits in reverse order.
3 *******************************************************/
4 #include
<iostream>
5 using namespace std;
6 int main()
7 {
8
int num;
//
to hold the value
9
10
/*--------------read a positive integer value------*/
11
cout << “\nEnter an integer value greater than zero:\t”;
12
cin >> num;
13
14
/*---- print its digits in reverse order -----------*/
15
cout <<
“\n\nIts digits in reverse order are as follows:\t”;
16
while (num != 0)
17
{
18
cout
<<
( num % 10 );
19
num = num / 10;
20
}
21
return ( 0 );
22 }
 The body-of-the-loop consists of the statements in lines 18 and 19.
 The loop-initialization statement is the input statement in line 12; and
 The loop-increment statement is in line 19.
110
Exercise 3.12
a. Specify an algorithm (using a flowchart) to read an integer value greater than 1
and to compute its greatest divisor that is less than the value itself. For
example, if the value is 15, the answer is 5, and if the value is 13, the answer is
1.
To compute the greatest divisor of an integer value n greater than 1 that is less
than n, repeatedly divide that value n by i= 2, then 3, then 4, . . . etc., until you
get a remainder of 0 or i *i>= n. If the remainder is 0, then the greatest divisor
is n/i, otherwise, it is 1.
b. Write the C++ code segment that corresponds to the algorithm in question a.
111
112
while Structure with one Statement in the Body-of- the-Loop
 When the body-of-the-loop consists of just one statement, the braces may be
omitted from the while structure.
Problem Statement
Write a program to compute the smallest power of 5 greater than 10000 (1, 5,
25, 125, . . . ).
Program Logic
Input:
none.
Output: the smallest power of 5 greater than 10000.
Note:
 To compute the smallest power of 5 greater than 10000, we need:
A variable power to hold the powers of 5.
It is initialized to 1 before the body-of-the-loop.
 The current value of variable power is multiplied by 5 in the body-of-theloop until it becomes greater than 10000.
 The loop condition is therefore: power <= 10000.
113
After
Value of
Iteration
variable power
-
1
1
1x5=5
2
5 x 5 = 25
3
25 x 5 = 125
.
.
.
Variable:
power (int) to hold the powers of 5.
Algorithm Specification (using Pseudo-Code)
1. Set variable power to 1: power = 1
2. As long as the current value of variable power is less than or equal
to 10000, do the following:
2.a
Multiply the current value of variable power by 5:
power = power * 5
3. Output the result.
114
115
116
Algorithm Specification (using a Flowchart)
Start
power = 1
False
power <= 10000
True
Power = power * 5
Stop
117
118
Figure 3.12
while Structure with a single statement in the body-of-the-Loop
Line Number
1
/********************************************************
2
Program to compute the smallest power of 5 greater
than 10000
3
********************************************************/
4
#include
<iostream>
5
using namespace std;
6
int main()
7
{
8
int power;
//
to hold the current power of 5
9
power = 1;
// first power of 5
10
while ( power <= 10000)
11
Power = power * 5;
12
13
/*-------------print the result-------------------*/
14
cout << endl << power
15
<< “ is the smallest power of 5 greater than 10000";
16
return (0);
17
}
 Although the body-of-the-loop consists of just one statement, it could also
be specified as a compound statement as follows:
while (power <= 10000)
{
power = power * 5;
}
119
Sentinel-Controlled Iteration
Problem:
 You want to process a list of values in a program.
 But the number of elements in the list may change from one execution of the
program to another.
One possible solution:
 Use a sentinel value (dummy value, flag value, or signal value) to mark the
end of the list.
Example:
87
69
95
65
73
86
93
68
-99
 A sentinel value is in general chosen in such a way that they can not possibly
be one of the data items in the list.
Example:
For a program to read and process a list of test scores received by
students in an exam, a sentinel value might be -1 or -99.
120
Accessing and processing the data
 The data items in the list are accessed and processed one at a time until the
sentinel value is accessed.
 However, the sentinel value must not be processed.
 The algorithm to perform this type of repetition is specified using a flowchart as
follows:
Read/Access the first data item
False
True
data item != sentinel
Process a data item
Read/Access the next data item
Next-Statement
121
 It is specified using the while structure as follows:
<statement-to read/access-the first-value>
While(<value-read/access != sentinel-value>)
{
<processing-statements>
<statement-to-read/access-the-next-value>
}
 <processing-statements> consists of one or more statements used to process
a data item in the list.
122
Problem Statement
Write a program to read one or more weight measurements in pounds and to
convert them into kilograms. The dummy value -99.0 is entered to end the input of
the weight measurements. Note that 1 Lb = .454 Kgs.
Program Logic
Input:
one or more weight measurement (in Lbs) followed by the sentinel value
-99.00.
Output:
weight measurements in (Kgs).
Variables:
pound (double) to hold a weight measurement in Lbs.
Algorithm Specification (using Pseudo-code)
1. Read the first weight measurement (in pound) or the dummy value -99.0 into
variable pound.
2. As long as the current value of variable pound is not the sentinel -99.0 do the
following:
2.a
convert it to kilogram and print the result.
2.b.
Read the next weight measurement (in pound) or the dummy value -99.0
into variable pound.
3. Write “Thank you”
123
Algorithm Specification (using a Flowchart)
Start
Read
pound
False
True
pound != -99
Write
.454 * pound
Read
pound
Write
“Thank you”
Stop
124
Figure 3.13
Sentinel-Controlled Iteration using the while Structure
Line Number
1 /************************************************************
2 Program to read one or more weight measurements in pounds and
3 to convert them into kilograms.
4 *************************************************************/
5 #include
<iostream>
6 #include
<iomanip>
7 using namespace std;
8
9 #define
COEFICIENT
.454
10 #define
DUMMYWEIGHT
-99.0
11
12 int main()
13 {
14
double
pound,
// the current weight measurement in Lb
15
16
cout setprecison(2) << fixed << showpoint;
17
18
/*read the first value or the dummy value -99.0 to stop -*/
19
cout
<<
endl
<< “Enter a weight measurement or -99.0 to stop:\t”;
20
cin
>>
pound;
21
while (pound != DUMMYWEIGHT)
22
{
23
cout << “\t = ” << (.454 * pound);
24
cout << endl << “Enter a weight measurement”
25
<< “ or -99.0 to terminate:\t”;
26
cin
>>
pound;
27
}
28
cout << endl << “Thank you”;
29
return (0);
30 }
Notice that there is an input statement before the while statement (line 20) and
another one as the last statement in the body of the loop (line 26).
125
Exercise 3.13
1. The following program that should read a list of integer values and compute
their sum until the sentinel value -99 is read, contains some error(s). Rewrite it
with these errors corrected.
#include <iostream>
using namespace std;
int main( )
{
int total, value;
cout << “\nEnter all values to add followed by” <<
-99 <<“ to stop\n”;
while ( value != -99 )
{
cin >> value;
total = total + value;
}
cout << endl << “The total of these value is:\t” <<total;
return( 0 );
}
2.a.
Specify an algorithm (using a flowchart) to read one or more temperature
values in Fahrenheit and to convert them to Celsius. The sentinel value -99
marks the end of the input temperatures.
You convert a Fahrenheit temperature to Celsius as follows: Celsius = 5.0 / 9
(Fahrenheit - 32).
2.b.
Write the C++ code segment that corresponds to the algorithm in question
2.a.
126
3.7 One-Way Selection using the if Structure
Purpose
To ask the CPU to perform some actions only if a test performed on a condition is
true.
 It is specified using a flowchart as follows:
False
condition
True
C-Statement
Next-Statement
C-Statement is one or more statements that specify the operations to
be performed when condition evaluates to true.
127
 It is specified in C++ language using the if structure as follows:
if (<condition>)
<Statement>
<Next-Statement>
where <Statement> is a single statement or a compound statement.
 Note that when <condition> evaluates to false, no action is performed.
Instead, the execution of the program continues with the execution of <NextStatement>.
128
Case Study 3.8
Problem Statement
A rebate of 5% is given in a store only if the total price of the merchandise is at
least $100.00.
Write a program to read the unit price and the number of quantity of the
merchandise, and to compute the amount of the purchase after the rebate if
applicable.
Program Logic
Input:
the unit price and the quantity of the merchandise.
Output:
the total amount of purchase.
Note:
 To read the unit price and the quantity of a merchandise and to compute the
amount of the purchase of this merchandise, we need the following:
 A variable unitPrice, to hold the unit price.
 A variable quantity, to hold the quantity of the merchandise purchased.
 A variable purchase, to hold the total amount of the purchase.
129
 After the input of the unit price and the quantity, we do the following:
 We first compute the total price,
 then we check to find out if it is greater than 100.00:
If it is, we compute the rebate and subtract it from the total price;
Otherwise nothing is done.
 Finally, the purchase price is printed.
Variables:
unitPrice ( double )
quantity ( int )
purchase ( double )
to hold the unit price.
to hold the quantity.
to hold the amount of purchase.
130
Algorithm Specification (using Pseudo-Code)
1. Read the unit price and the quantity of the merchandise into variables
unitPrice and quantity respectively.
2. Compute the total price of the merchandise:
purchase = unitPrice * quantity.
3. If the total price of the merchandise is 100.00 or more, do the following:
3.a
compute the rebate and subtract it from the total price:
purchase = purchase - .05 * purchase.
4. Print the amount of purchase.
131
Algorithm Specification (using a Flowchart)
Start
Read
unitPrice, quantity
purchase = unitPrice * quantity
False
purchase >= 100.00
True
purchase = purchase - .05 * purchase
Write
purchase
Stop
132
Figure 3.14
One-Way Selection using the if Structure
Line Number
1 /*********************************************************
2 Program to compute the total amount of purchase in a store
3 *********************************************************/
4 #include
<iostream>
5 using namespace std;
6 int main()
7 {
8
const double MINPURCHASE = 100.00; //minimum purchase
9
const double RRATE = 0.05;
// rebate rate
10
double unitPrice,
// unit price
11
Purchase;
// amount of purchase
12
int quantity;
// number of quantity
13
14
/*-----read in the unit price and the quantity -------*/
15
cout << “\nEnter the merchandise unit price:\t”;
16
cin
>> unitPrice;
17
cout << ‘\nEnter its quantity:\t”;
18
cin
>> quantity;
19
20
/*----------compute the amount of purchase -----------*/
21
purchase = unitPrice * quantity;
22
if(purchase >= MINPURCHASE)
23
purchase = purchase - RRATE * purchase;
24
25
/*---------- print the amount of purchase ------------*/
26
cout << “\nYour total amount of purchase is:\t”
27
<<
purchase;
28
return( 0 );
29 }
133
The Null Statement
 The null statement is a statement that consists of just the semicolon.
 It says to do nothing, but to continue with the next operation.
 You may also use the if-else structure and the null statement to specify a
one-way selection as follows:
if (<condition>)
<Statement>
else;
<Next-Statement>
Example:
The if structure in lines 22 and 23 of the program in Figure 3.19 could be
written as follows:
if (purchase >= 100.00 )
purchase = purchase - RRATE * purchase;
else;
/*-------------- print the amount of purchase --------------*/
cout << “\nYour total amount of purchase is:\t”
<< purchase;
134
Exercise 3.14
1. What is the output of the following program segment for each of the following
input values?
a. input value: 4
b. input value: 20
cin >> num;
if( num >= 5)
{
pnum = num + 7;
cout << endl << “pnum=\t” << pnum;
}
cout << “result=\t” << (num - 1);
2a.In a department store, a 10% rebate is given for every purchase of at least $
20.00. Specify an algorithm (in pseudo-code and using a flowchart) to read the
unit price of a product, the quantity purchased, and to compute the amount of
the purchase after the rebate if applicable.
2.b. Write the C++ code segment that corresponds to the algorithm in question 2.a.
135
3.8 Multiple-Way Selection using if-else Structures
Purpose
 To ask the CPU to select the action to be performed from a list of three or more
actions based on the true values of two or more conditions.
136
A multiple-way selection with four actions and three conditions is specified using a
flowchart as follows:
True
condition1
Action-1
True
Action-2
False
condition2
True
False
condition3
Action-3
False
Action-4
Next-Action
 Condition1 is first tested, and if it is true, Action-1 is executed, followed by
Next-Action;
 Otherwise, condition2 is tested, and if it is true, Action-2 is executed,
followed by Next-Action;
 Otherwise, condition3 is tested, and if its true, Action-3 is executed,
followed by Next-Action;
 Otherwise, Action-4 is executed, followed by Next-Action.
 Note that only one of the actions, Action-1, Action-2, Action-3, or Action-4 is
executed.
137
 In some situations, Action-4 may also be the null action.
 This behavior is specified in C/C++ using if-else structures as follows:
if ( <condition1> )
<Statement-1>
else if ( <condition2> )
<Statement-2>
else if ( <condition3> )
<Statement-3>
else
<Statement-4>
<Next-Statement>
 <Statement-1>, <Statement-2>, <Statement-3>, and <Statement-4> are single
or compound statements that specify respectively, Action-1 , Action-2 , Action-3
, and Action-4 .
 <Next-Statement> is a statement that specifies the Next-Action.
138
 In the case that <Statement-4> is the null statement, this behavior may also be
specified as follows:
if ( <condition1> )
<Statement-1>
else if ( <condition2> )
<Statement-2>
else if ( <condition3> )
<Statement-3>
<Next-Statement>
139
Case Study 3.9
Problem Statement
Four letters M, S, D, and W are used to encode the marital status of an
individual as follows: M (married), S (single), D (divorced), and W
(widowed). Any other character is considered invalid. Write a program to
read a marital code and to output the corresponding marital status.
Program Logic
Input:
a marital code (capital M, S, D, or W).
Output:
a marital status. Any other character is considered invalid.
Variables:
mcode
(char )
to hold the marital code.
140
Algorithm Specification (using a Flowchart)
Start
Read
mcode
True
mcode = ‘M’
False
True
False
mcode = ‘S’
Write
“married”
True
mcode = ‘D’
False
Write
“single”
True
Write
“divorced”
Write
“Widowed”
Stop
Mcode = ‘W’
False
Write
“invalid
”
141
Figure 3.15
Multiple-Way Selection using if-else Structures
Line Number
1
/****************************************************************
2
Program to read a marital code and to output the corresponding
3
marital status.
4
****************************************************************/
5
#include
<iostream>
6
using namespace std;
7
int main()
8
{
9
char mcode;
// to hold a marital code
10
11
/*------------------read in a marital code------------------*/
12
cout
<<
“\nEnter a marital code:\t”;
13
cin
>>
mcode;
14
15
/*---determine and print the corresponding marital status --*/
16
if (mcode == ‘M’)
17
cout
<<
“\nThis individual is married”;
18
else if (mcode == ‘S’)
19
cout
<<
“\nThis individual is single”;
20
else if (mcode == ‘D’)
21
cout
<<
“\nThis individual is divorced”;
22
else if (mcode == ‘W’)
23
cout
<<
“\nThis individual is a widow”;
24
else
25
cout << “\nThe marital code is invalid”;
26
return( 0 );
27
}
142
Exercise 3.15
A florist sells four different types of bouquets of flowers that he has numbered 101,
202, 303, and 404. The unit price of each of these bouquets of flowers is given as
follows:
ITEM NUMBER
UNIT PRICE
101
$ 5.25
202
$ 3.10
303
$ 9.75
404
$ 6.50
a. Specify an algorithm (using a flowchart) to read an item number and the
number of bouquets of that type purchased and to compute and print the total
price of those bouquets.
b. Write the C++ code segment that corresponds to the algorithm in question a.
143
Case Study 3.10
Problem Statement
Write a program to read a test score and to determine and print the
corresponding letter grade as follows: A ( score >= 90.00), B (80.00 <= score
< 90.00), C (70.00 <= score <80.00)
D (60.00 <= score < 70.00), and F
(score < 60.00). It is assumed that all test scores are valid.
Program Logic
Input:
Output:
a test score (floating-point value in the range 0.00 to 100.00).
the corresponding letter grade.
Variables: score (double ) to hold a test score.
144
Algorithm Specification Using a Flowchart
Start
Read
score
True
score >= 90.00
False
True
False
score >= 80.00
Write
‘A’
True
Write
‘B’
Score >= 70.00
Write
‘C’
False
True
False
score >= 60.00
Write
‘D’
Stop
Write
“invalid
”
145
Figure 3.16
Multiple-Way Selection using if-else structures
Line Number
1
/****************************************************************
2
Program to read a test score and to determine and output the
3
corresponding letter grade.
4
****************************************************************/
5
#include
<iostream>
6
using namespace std;
7
int main()
8
{
9
double score;
// to hold a test score
10
11
/*------------------read in a test score--------------------*/
12
cout
<<
“\nEnter a test score:\t”;
13
cin
>>
score;
14
15
/*----determine and print the corresponding letter grade ---*/
16
if ( score >= 90.00)
17
cout <<
“\nThe letter grade is:\t” <<
‘A’;
18
else if (score >= 80.00)
19
cout << “\nThe letter grade is:\t”
<<
‘B’;
20
else if (score >= 70.00)
21
cout << “\nThe letter grade is:\t”
<<
‘C’;
22
else if (score >= 60.00)
23
cout << “\nThe letter grade is:\t”
<<
‘D’;
24
else
25
cout << “\nThe letter grade is:\t”
<<
‘F’;
26
return ( 0 );
26
}
146
 The multiple-way selection specified in line 16 to line 25 could also be
written as follows:
if ( score < 60.00)
cout << “\nThe corresponding letter grade is:\t” << ‘F’;
else if (score < 70.00)
cout << “\nThe corresponding letter grade is:\t” << ‘D’;
else if (score < 80.00)
cout << “\nThe corresponding letter grade is:\t” << ‘C’;
else if (score < 90.00)
cout << “\nThe corresponding letter grade is:\t” << ‘B’;
else
cout << “\nThe corresponding letter grade is:\t” << ‘A’;
147
Exercise 3.16
1.a.
What is the output of the following program segment for the specified
input values:
a. input value: 3
b. input value: 7
c. input value: 12
cin >> num;
if (num < 5)
cout << "Red\t";
else if (num < 10)
cout
<< "Yellow\t";
else
cout
<< "Green\t";
cout << “blue”
1.b.
For what range of values is the output respectively:
a) Red Blue.
2.a.
b) Yellow Blue.
c) Green Blue.
The decision table below shows fines imposed for speeding violations.
Specify an algorithm (using a flowchart) to read the speed of a car and to output
the corresponding fine.
2.b.
2.a.
Speed <= 50 mph
Fine = $ 0.00
50 < Speed <= 70
Fine = $ 15.00
70 < Speed <= 80
Fine = $ 30.00
Speed > 80
Fine = $ 60.00
Write the C++ code segment that corresponds to the algorithm in question
148
Case Study 3.11
Problem Statement
A car dealer offers a rebate on three different types of car as follows:
Mid-size cars
$ 300.00
Sedans
$ 500.00
Trucks
$ 700.00
And each type of car is encoded by an integer value as follows:
Small cars
1
Mid-size cars
2
Sedans
3
SUVs
4
Trucks
5
He wants you to write a program to read the list price of a car and the code of its
type, and to do the following:
 Determine if there is a rebate on that car:
if there is a rebate, print the rebate and compute the price of the car with
the rebate.
 Compute the sale tax (8.25 % of the price after the rebate).
 Compute the total price of the car and print it.
Assume that the user of your program always enter a valid code for the type of car.
149
Program Logic
Input:
the price of a car and the code of its type.
Output:
the total price of the car.
variables:
price
(double) to hold the price of the car.
saleTax (double) to hold the sale tax on the car.
carType (int)
to hold the code of the type of the car.
Algorithm Specification (using Pseudo-code)
1. Read the list price and the code of the type of the car.
2. If the code of the type of this car is either 2, 3, or 5, do the following:
2.1
print the rebate received.
2.2
compute the price of the car after the rebate.
3. Compute the sale tax.
4. Compute the total price of the car and print it.
150
Algorithm Specification (using a Flowchart)
Start
Read
Score, carType
True
False
carType = 2
True
carType = 3
Write
300
False
True
price = price - 300
False
carType = 5
Write
500
Write
700
price = price - 500
price = price - 700
saleTax = .0825 * price
Write
price + saleTax
Stop
151
Figure 3.17
Implementing a Multiple-way Selection without default-Action
Line Number
1
/****************************************************************
2
Program to compute the total price of a car with the dealer’s
3
rebate.
4
****************************************************************/
5
#include
<iostream>
6
using namespace std;
7
8
#define
TAXRATE
0.0825
/* tax rate of 8.25 % */
9
#define
MIDREBATE 300.00
/* rebate on mid-size cars */
10
#define
SEDANREBATE 500.00
/* rebate on sedans */
11
#define TRUCKREBATE 700.00
/* rebate on trucks */
12
13
int main()
14
{
15
double price,
// to hold the car price
16
saleTax;
// to hold the sale tax on the car
17
int carType;
// to hold the code of the type of the car
18
19
/*– read the list price and the code of the type of the car */
20
cout << “\nEnter the list price and ”
21
<< “ the code of the type of the car in this order:\t”;
22
cin
>>
price
>>
carType;
23
24
/*------------ find out if the car has a rebate ----------*/
25
if ( carType == 2)
26
{
24
cout
<< “\n This car rebate is:\t$” <<
MIDREBATE;
27
price = price - MIDREBATE;
28
}
29
else if ( carType == 3)
30
{
31
cout
<<
“\n This car rebate is:\t$” <<
SEDANREBATE;
32
price = price - SEDANREBATE;
33
}
34
else if ( carType == 5)
35
{
36
cout <<
“\n This car rebate is:\t$” <<
TRUCKREBATE;
37
price = price - TRUCKREBATE;
36
}
38
39
/*------ compute and print the total price of the car ------*/
40
saleTax = price * TAXRATE;
41
cout << “\n The price of the car is:\t$” <<(price + saleTax);
42
return( 0 );
43
}
152
Exercise 3.17
A game consists of selecting a positive integer value and rewarding bonuses to the
player according to the remainder in the division of that integer value by 5 as
follows:
REMAINDER
BONUS
0
200
1
350
2
400
3
500
4
750
a. Specify an algorithm (using a flowchart) to read a positive integer value and to
output the bonus received by the user.
b. Write the C++ code segment that corresponds to the algorithm in question a.
153
3.9 Tracing the Execution of a Program
Example 1:
Given the following definitions of variables:
int num1 = 5, num2, result = 0;
Trace the execution of the following program segment for each of the following
input values:
a. input value: 8
b. input value: 3
Line Number
Statement
1
cin
2
if(num1 > num2)
3
4
5
6
7
>> num2;
result = num1 + 4;
if (num2 < 7)
num1 = num2 + num1;
else if (num2 > 10)
num1 = 2 * num1;
8
result = result + num1 + num2;
9
cout << result;
154
a. Trace for input value: 8
Line Number
Variables
num1 num2
result
Output:
13
-
5
?
0
1
5
8
0
2
5
8
0
4
5
8
0
6
5
8
0
8
5
8
13
9
5
8
13
b. Trace for input value: 3
Line Number
Variables
num1 num2
result
-
5
?
0
1
5
3
0
2
5
3
0
3
5
3
9
4
5
3
9
5
8
3
9
8
8
3
20
9
8
3
20
Output:
20
155
Exercise 3.18
Trace the execution of the code segment in the example above for each of the
following input values:
a. input value: 2
b. input value: 6
Example 2:
Given the following definitions of variables:
int ndx = 10, num, result = 0;
Trace the execution of the following program segment:
Line Number
Statement
1
num = 0;
2
while( ndx > 7 )
3
{
4
num = num + 3;
5
result = result + num + ndx;
6
ndx = ndx - 2;
7
}
8
cout << “\nndx =\t” << ndx;
9
cout << “\nresult=\t” << result;
156
Trace:
Line Number
Variables
ndx
num
Output:
result
-
10
?
1
10
0
0
2
10
0
0
4
10
3
0
5
10
3
13
6
8
3
13
2
8
3
13
4
8
6
13
5
8
6
27
6
6
6
27
2
6
6
27
8
6
6
27
9
6
6
27
ndx = 6
0
result = 27
157
Exercise 3.19
Trace the execution of the following program segments:
1 ndx = 1;
2 pnum = 60;
3 while(ndx < 5)
{
4
pnum = pnum / ndx;
5
ndx = ndx + 2;
}
6 cout << “\npnum=” << pnum
<< “\nndx=” << ndx;
158
Hands-On Exercises
1.
a. Specify an algorithm (using a flowchart) to read an integer value and to
determine if it is a multiple of 7. If it is a multiple of 7, print it with the
message “MULTIPLE OF 7”, otherwise, print it with the message NOT
MULTIPLE OF 7.”
b. Write the C++ code segment that corresponds to the algorithm in question
1.a.
2.
A department store awards bonuses to customers according to the price of the
items purchased as follows:
If the price is greater than $100.00, then the bonus is 10 %; of the price;
otherwise, it is 5 % of the price.
a. Specify an algorithm (using a flowchart) to read the unit price and the
number of items of a product that a customer has purchased and to compute
and print the price of that product and the bonus awarded.
b. Write the C++ code segment that corresponds to the algorithm in question
2.a.
3 a. Specify an algorithm (using a flowchart) to read two integer values and to do
the following: if the first value is greater than the second, add 3 to the first value,
and compute the sum and the difference of the new first value minus the second,
and print the results; otherwise, subtract 2 from the first value, and compute the
product of the new first value and the second, and the quotient in the division of
the second value by 2, and print the results. Regardless of the values read,
compute two times the new first value minus the second value, and print the result.
b. Write the C++ code segment that corresponds to the algorithm in question
3.a.
159
4. a. Specify an algorithm (using a flowchart) to read a character value and to
determine if it is a letter of the alphabet. If it is, print it with the message
“LETTER”; otherwise print it with the message “NOT A LETTER.”
b. Write the C++ code segment that corresponds to the algorithm in question
4.a.
5. a. A client has purchased 20 products in a store. Specify an algorithm (using a
flowchart) to read the unit price and the number of items of each product and to
compute its price (number items times the unit price). Also compute and print the
total price of all these products.
b. Write the C++ code segment that corresponds to the algorithm in question
5.a.
6. a. Specify an algorithm (using a flowchart) to add the first 20 positive integer
values ( 1 + 2 + 3 + . . . + 20) and to output the result.
b. Write the C++ code segment that corresponds to the algorithm in question
6.a.
7. a. Specify an algorithm (using a flowchart) to read a double precision floatingpoint value, to calculate its 6th power ( n * n * n * n * n * n), and to output the
result.
b. Write the C++ code segment that corresponds to the algorithm in question
7.a.
8. a. Specify an algorithm (using a flowchart) to read 20 non zero integer values
and to count the number of positive values and the number of negative values, and
to output the results.
160
b. Write the C++ code segment that corresponds to the algorithm in question
8.a.
9. a. Specify an algorithm (using a flowchart) to read 20 non zero integer values
and to compute the average of positive values and the average of negative values,
and to output the results.
b. Write the C++ code segment that corresponds to the algorithm in question
9.a.
10. A store has 120 units of a product and every time there is a sale, the amount
of units sold is deducted from the stock until it becomes less than or equal to 30.
The manager of the store must then place a new order.
a. Specify an algorithm (using a flowchart) to read the number of units sold daily
and to update the current stock until it becomes less than or equal to 30. The
message “place a new order” and the amount of units to purchase in order to have
120 units are then printed.
b. Write the C++ program that corresponds to the algorithm in question a.
11.
a. Specify an algorithm (using a flowchart) to read the prices of one or more
books, and to compute their average price. Book prices are input one after another,
and terminated with the sentinel value -99.00.
b. Write the C++ code segment that corresponds to the algorithm in question
11.a.
12.
a. Specify an algorithm (using a flowchart) to read one or more positive
integer values and to compute their product. The sentinel value 0 marks the end of
the input values.
b. Write the C++ program that corresponds to the algorithm in question 12.a.
13.a. Specify an algorithm (using a flowchart) to read the test scores of one or
161
more students (until the sentinel value -99 is read) and to compute their average.
b. Write the C++ code segment that corresponds to the algorithm in question
13.a.
14.
a. greatt, smallt, and somet are integer variables with some initial values.
Specify an algorithm (using a flowchart) to read an integer value into variable num
and to do the following: add 1 to smallt if the value read is less than 5; then add 2
to greatt if the value read is greater than 20, otherwise subtract 3 from smallt.
Then, regardless of the value read add 7 to somet.
b. Write the C++ code segment that corresponds to the algorithm in question
14.a.
15.
a. small_ct, middle_ct, large_ct, and sum are integer variables with some
initial values. Specify an algorithm (using a flowchart) to carry out the following
tasks: read a value into the integer variable num and if the value read is greater
than 100, add 1 to variable large_ct; if it is less than 50, add 2 to variable small_ct;
otherwise, add 3 to variable middle_ct; regardless of the value read, add it to
variable sum.
b. Write the C++ code segment that corresponds to algorithm in question 15.a.
16.
a. Specify an algorithm (using a flowchart) to read 50 integer values and
determine and print the number of even values.
b. Write the C++ code segment that corresponds to the algorithm in question
16a.
17.
a. Specify an algorithm (using a flowchart) to read one or more integer
values and to compute the average of positive values and print it. If there are no
162
positive values, print an appropriate message.
b. Write the C++ program that corresponds to the algorithm in question 17.a.
18.
a. Specify an algorithm (using a flowchart) to read an integer value, an
operator ( +, -, *, %, or / ), and another integer value in this order (for example, 23
+ 5), and to compute the expression consisting of the first value, followed by the
operator, which is followed by the second value, and to output the result. Note that
in the division of the first value by the second, you must make sure that the second
value is not zero.
b. Write the C++ code segment that corresponds to the algorithm in question
18.a.
19.
A department store offers rebates to customers according to the price of the
items purchased as follows:
Price >= $ 100.00
Rebate = $ 10.00
$ 50 <= Price < $ 100.00
Rebate = $ 5.00
$ 20 <= price < $ 50.00
price < $ 20.00
Rebate = $ 2.00
No rebate
A sale tax of 8.25% is also imposed on the price of each purchase (after the
rebate, if any).
a. Specify an algorithm (using a flowchart) to read the unit price and the
number of items purchased of a product, and to output the rebate received by
the customer, the total price (including the rebate), and the amount due
(including taxes).
b. Write the C++ code segment that corresponds to the algorithm in question
19a.
163
20.
Write a program segment to read a character from the keyboard and to
determine if it is a letter (‘a’ - ‘z’ or ‘A’ - ‘Z’), a digit (‘0' - ‘9'), or a special
character (any other character). If it is a letter, print the message “letter”; if it is a
digit, print the message “digit”; and if it is a special character, print the message
“special character”.