Post on 11-Mar-2020
© 2013 Gilbert Ndjatou Page 57
Control Structures
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.
The single-way selection, the two-way selection, the multiple-way selection, the counter-controlled
iteration and the logically-controlled iteration are collectively called control structures.
The specification of a controlled structure depends on a logical expression called condition.
Controlled structures may also be specified using the following flowchart symbols:
Flowchart Symbols
SYMBOL
(a)
(b)
(c)
(d)
(e)
(f)
NAME
Terminal
Input/Output
Process
Flow Lines
Decision
Connector
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.
© 2013 Gilbert Ndjatou Page 58
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.
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
Evaluations 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’;
Evaluate the following conditions:
a) num1 >= 5 d) num2 + 3 == num3 * 4
b) fnum + 7.2 != fnum / 2 e) 3 * num1 + 4 < num3 * 2
c) fnum * 2 > num1 + 20 f) ‘A’ <= ch
© 2013 Gilbert Ndjatou Page 59
Solutions
a) num1 >= 5 d) num2 + 3 == num3 * 4
5 >= 5 7 + 3 == 2 * 4
True 10 == 8
False
b) fnum + 7.2 != fnum / 2 e) 3 * num1 + 4 < num3 * 2
11.75 + 7.2 != 11.75 / 2 3 * 5 + 4 < 2 * 2
18.95 != 5.875 19 < 4
True False
c) fnum * 2 > num1 +20 f) ‘A’ <= ch
11.75 *2 > 5 + 20 ‘A’ <= ‘K’
13.75 > 25 True
False
Characters are ordered according to their ASCII code representations:
‘0' < ‘1' < ‘2' < . . . < ‘9' < ‘A’ < . . . < ‘Z’ < ‘a’ . . . < ‘z’.
Relational operators have a lower precedence than arithmetic operators:
o 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.
For example: (fnum * 2) > (num1 + 20)
Compound Conditions
A compound condition is built from simple conditions using logical operators.
Logical Operators
C++ Symbol Meaning Evaluation
&&
AND
<condition1> && <condition2> is true if and only if
both conditions are true
||
OR
<condition1> || <condition2> is true if and only if at
least one of the two conditions is true
! NOT !<condition> is true if and only if <condition> is false
© 2013 Gilbert Ndjatou Page 60
Evaluations of compound conditions
True || True True || False False || True False || False
True True True False
True && True True && False False && True False && False
True False False False
There is a short-circuit evaluation of a compound condition when you do not have to evaluate the
right-most condition in order to get the true value of the compound condition:
True || True and True || False Therefore True || -
True True True
Also,
False && True and False && False Therefore False && -
False False False
Exercise CS1*
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)
© 2013 Gilbert Ndjatou Page 61
Precedence of C/C++ Operators
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.
Exercise CS2
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) num1 + 5 = = 24 || num1 – 1 > num2 – 5
e) 2 * num1 - 5 >= 9 && fnum / 2 + 10 <= 6.5
f) num1 - num2 <= num1 / 3 || num1 * num2 > 100
g) num1 - 5 >= num3 || num2 < 15 && num1 >= 9
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
© 2013 Gilbert Ndjatou Page 62
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;
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.
Evaluation of True and False
In the C/C++ programming language,
false is represented by the integer value 0, and
any value other than 0 represents true.
Therefore, the following two conditions are equivalent (have the same true value):
o Conditions value != 0 and value (value is not zero means that it is true)
o Conditions value == 0 and ! value (value is zero means that !value is true)
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);
© 2013 Gilbert Ndjatou Page 63
Exercise CS3
1. Which of the following conditions are equivalent (that means have the same true value)?
a) num != 0 d) !num
b) num == 0 e) !(num == 0)
c) num
2. 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 the 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.
e. he is either 6.0 feet tall, or he has less than 4 children.
f. he is not older than 35 and he has 2 or 3 children
© 2013 Gilbert Ndjatou Page 64
Two-Way Selection using the if-else Structure
The solutions of some problems require the CPU to test a condition and to select the action to be
performed based on whether or not that condition is true.
Example:
Suppose that at a party, you serve alcohol drinks only to guests who are 21 or older, and a juice to
guests who are less than 21.
When a guest comes to get a drink, you first test his age: if he is 21 or older, you serve him an
alcohol drink; otherwise you serve him a juice.
The solutions of these types of problems are written using a two-way selection structure which is
specified using a flowchart as follows:
False True
It says to do the following:
Test condition
a. if it is true, perform the actions (T-Action) specified by T-Statement,
b. otherwise, perform the actions (F-Action) specified by F-Statement.
Next-Statement is the statement that says what to do after any of the actions (F-Action or T-Action)
above has been executed.
A two-way selection structure is specified in C++ using the if - else structure as follows:
if (<condition>)
<T-statement>
else
<F-statement>
<Next-Statement>
Condition
F-Statement T-Statement
Next-Statement
© 2013 Gilbert Ndjatou Page 65
<T-statement> is a single statement that specifies the T-Action
<F-statement> is a single statement that specifies the <F-Action>.
Case Study CS1
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.”
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)
False True
start
Read
age
age >= 21
Write “Thank you for
using this program”
Stop
Write “serve alcohol drink”
Write
“serve a juice”
© 2013 Gilbert Ndjatou Page 66
Figure CS1 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 21
int main()
{
int age; // 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);
}
Case Study CS2
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.
© 2013 Gilbert Ndjatou Page 67
Algorithm Specification (using a Flowchart)
False True
Figure CS2 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) // it is even
cout << endl << num << “\tEVEN”;
else // it is odd
cout << endl << num << “\tODD”;
return ( 0 );
}
Exercise CS4
Write a C++ code segment 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.”
Start
Read
num
num % 2 = 0
Write
num, “odd”
Write
num, “even”
Stop
© 2013 Gilbert Ndjatou Page 68
Exercise CS5
Write a C++ code segment to read a character and to determine if it is a letter of the alphabet. If it is a
letter of the alphabet, print it with the message, “it is a letter” otherwise, print it with the message, “it is
not a letter.”
Compound Statement
A compound statement has the following syntax:
{
(One or more statements to be executed as a block)
}
Example
{
num2 = num1 + 5;
num1 = num1 +1;
cout << endl << “num1=\t” << num1 << “\n num2=\t” << num2;
}
The statements of a compound statement are executed one after another, starting with the first one in
the sequence.
A compound statement may appear anywhere in a C++ program where a single statement may
appear.
If you have to specify two or more statements as the T-statement or the F-statement of an if-else
structure, these statements must be specified as a compound statement.
Case study CS3
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.”
© 2013 Gilbert Ndjatou Page 69
Program Logic
Output: the quotient and the remainder in the division of the second value by the first or the
message “0 is invalid divisor” depending on the input.
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.
Algorithm Specification (using a Flowchart)
False True
Start
Read
divisor
divisor == 0
Write
divisor
“invalid divisor”
Read
dividend
Write
dividend / divisor
dividend % divisor
Write
“Thank you”
Stop
© 2013 Gilbert Ndjatou Page 70
Figure CS3 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, // to hold the first value
dividend; // to hold the second value
/*---------------------- read in the divisor-----------------------*/
cout << “\n\nEnter the divisor please:\t”;
cin >> divisor;
/*-----read the dividend and compute the quotient and the remainder--*/
if (divisor == 0) // it is invalid
cout << endl << divisor << “\tIS INVALID DIVISOR”;
else
{
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 );
}
Exercise CS6*
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);
© 2013 Gilbert Ndjatou Page 71
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;
Exercise CS7*
Trace the execution of the following program segment and show its output for each of the following
input values:
a. input: 4 b. input: 20
Line # Statements
1 cin >> num;
2 if (num <10 )
{
3 num = num + 6;
4 cout << endl << “num =\t” << num;
}
else
5 cout << endl << “num / 4 =\t” << (num 4);
6 cout << endl << “result =\t” << (2 * num);
Exercise CS8
Write a C++ code segment to read an integer value into variable num1and another integer value into
variable num2 and to do the following: if the value in variable num1 is greater than the value in variable
num2 do the following: add 1 to the value in num1 and 5 to the value in num2 and then print the result
of the product of the new value in num1 and the new value in num2; otherwise, do the following:
subtract 1from the value in num1 and 5 from the value in num2 and then print the result of the product of
the new value in num1 and the new value in num2.
Exercise CS9
A department store offers a rebate of 5% if the total amount of the purchase is at least 100 and a rebate
of 2% otherwise. A sale tax of 8.25 % is also imposed on the price of each purchase (after the rebate).
Write a C++ code segment to read the unit price and the number of items purchased, and to output the
amount of the rebate and the price (including taxes) of the purchase.
© 2013 Gilbert Ndjatou Page 72
Counter-Controlled Iteration using the while Structure
The solutions of some problems require the CPU to repeat the execution of one or more statements a
certain 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 solutions of these types of problems are written using a counter-controlled iteration (or loop)
which is specified using a flowchart as follows:
False True
Body-of- the- Loop consists of the statements whose executions are repeated by the CPU.
counter is called 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.
Initial/Final Value
If the initial value is 0 (no execution is done yet), then the final value must be the number of
executions.
If the initial value is 1 (one execution is about to be done), then the final value must be the 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.
counter = initial-value
Counter < final-value
Body-of-the-Loop
Next-Statement
© 2013 Gilbert Ndjatou Page 73
Algorithm of the Candy Bar Machine (using a flowchart)
False True
Specification of a Counter-Controlled Iteration in C++
A counter-controlled iteration may be specified in C++ using the while structure as follows:
counter = initial-value;
while (counter < final-value)
{
<Body-of-of the-loop (including the increment-statement)>
}
<Next-statement>
Start
count = 0
count < 7
Read
coin
count = count + 1 Write
“Thank you”
Stop
total = 0
total = total + coin
© 2013 Gilbert Ndjatou Page 74
Algorithm for the Candy Bar Machine Problem (in C++)
int total, // to hold the total value of the coins
coin, // to hold the value of a coin
count; // to hold the number of repetitions
total = 0;
count = 0;
while ( count < 7 )
{
cin >> coin;
total += coin;
count ++;
}
cout << endl << “Thank You”;
Case Study CS4
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 Lbs).
Output: 30 weight measurements (in Kgs).
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.
© 2013 Gilbert Ndjatou Page 75
Algorithm Specification (using a flowchart)
False True
Figure CS4 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.h>
6 #include <iomanip.h>
7 #define MAXCOUNT 30
8 #define COEFICIENT .454
9
10 int main()
11 {
12 int count; // to count weight measurements
13 double pound, // the current weight measurement in Lbs
14
Start
count = 0
count < 30
Read
pound
Write
.454 * pound
count = count + 1
Write
“Thank you”
Stop
© 2013 Gilbert Ndjatou Page 76
15 cout << fixed << showpoint << setprecision(2);
16
17 /*read all weight measurements (Lbs) and convert them to Kgs*/
18 count = 0; // no weight measurement is read so far
19 while (count < MAXCOUNT) // repeat thirty times
20 {
21 cout << “\nEnter a weight measurement please:\t”;
22 cin >> pound;
23 cout << “\t = ” << (.454 * pound);
24 count ++;
25 }
26
27 cout << endl << “Thank you”;
28 return (0);
29 }
The body of the loop consists of the statements in line 21 to line 24.
The loop-counter is initialized in line 18; and the loop-increment statement is in line 24.
Exercise CS10*
Assuming that all variables are properly defined, find the mistake(s) in the specification of each of the
following while structures:
a. b. c.
while( count < 10 ) while(count < 10) count = 0;
{ { while(count < 10 )
cin >> num; count = 0; {
cout << 2 * num; cin >> num; cin >> num;
count = count + 1; cout << 2 * num; cout << 2 * num;
} count = count + 1; }
}
Exercise CS11
Write a C++ code segment 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).
© 2013 Gilbert Ndjatou Page 77
Using a Running Total
A running total is a variable that is used to compute the sum of the values processed at ach 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 CS5
Problem Statement Write a program to read 20 integer values and to compute their sum.
Program Logic
Input: 20 integer values.
Output: 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.
Algorithm Specification (using a Flowchart)
False True
Start
totalValue = 0
count = 0
count < 20
totalValue = totalValue + value
Read
value
count = count + 1 Write
totalValue
Stop
© 2013 Gilbert Ndjatou Page 78
Figure CS5 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 20
7
8 int main()
9 {
10 int count; // to count values
11 value, // to hold the value read
12 totalValue; // the hold the sum of the values read so far
13
14 /*------read all values and compute their sum-------*/
15 totalValue = 0;
15 count = 0; // no value has been read so far
16 while (count < MAXCOUNT) // repeat twenty times
17 {
18 cout << “\nEnter an integer value please:\t”;
19 cin >> value;
20 totalValue += value;
21 count++;
22 }
23
24 /*-----print the sum of all the values read----------*/
25 cout << “\n\nThe sum of all the values read is:\t”
26 << totalValue;
27 return (0);
28 }
Exercise CS12*
Each of the following code segments is supposed to read 10 integer values and to compute their sum.
What is wrong in each of these code segments?
a. b.
count = 0; count = 0;
while (count < 10 ) while (count < 10 )
{ {
sum = 0; cin>>num;
cin >> num; sum = sum + num;
sum = sum + num; count = count + 1;
count = count + 1; }
} cout << endl << sum;
cout << endl << sum;
© 2013 Gilbert Ndjatou Page 79
Exercise CS13*
Write a C++ code segment to read the test scores of twenty students and to compute and print their
average.
Exercise CS14
A client has purchased 20 products in a store. Write a C++ code segment to read the unit price and the
number of items of each product and to compute and print the total price of all these products.
Case Study CS6
Problem Statement
Write a program to compute the sum of the first 20 positive even integer values (2, 4, . . .).
Program Logic
Input: none.
Output: 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 a Flowchart)
False True
Start
totalValue = 0
count = 1
count < 21
totalValue = totalValue + 2 * count
count = count + 1
Write
totalValue
Stop
© 2013 Gilbert Ndjatou Page 80
Figure CS6 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 += 2 * count;
18 count ++;
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 }
Exercise CS15
Write a C++ code segment to add the first 20 positive multiples of 5 ( 5 + 10 + 15 + 20 + . . . ) and to
output the result.
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 CS7
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!
© 2013 Gilbert Ndjatou Page 81
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
After
Iteration Value of number value of factorial
- n 1
1 n - 1 1 x n
2 n - 2 1 x n x (n - 1)
.
.
.
n - 1 1 1 x n x (n - 1) x . . . x 2
Algorithm Specification (using a Flowchart)
False True
Start
Read
number
factorial = 1
number > 1
Factorial = factorial * number
number = number - 1
Write
factorial
Stop
© 2013 Gilbert Ndjatou Page 82
Figure CS7 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 *= number;
19 number --;
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.
Exercise CS16
Write a C++ code segment to generate the squares (n*n) of the integer values 20, 18, 16, 14, . . . , 2,
starting with 20.
Exercise CS17
Write a C++ code segment to read ten integer values and to compute and print their product.
© 2013 Gilbert Ndjatou Page 83
Logically-Controlled Iteration using the while Structure
The solutions of a class of problems require the CPU to repeat the execution of one or more statements
as long as a certain condition is true (that means, until a certain condition becomes false).
Case Study CS8
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.
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 values of the coins read so far.
It is initialized to 0 before the body-of-the-loop.
The loop condition is: totalValue < 100.
Variables:
coinValue ( int ) to hold the value of a coin.
totalValue ( int ) to hold the total value of the coins deposited so far.
© 2013 Gilbert Ndjatou Page 84
Algorithm Specification (using a Flowchart)
False True
Start
totalValue = 0
totalValue < 100
Read
coinValue
totalValue = totalValue + coinValue
Write
“Thank you”
Write
totalValue - 100
Stop
© 2013 Gilbert Ndjatou Page 85
Figure CS8 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 while( totalValue < SODAPRICE )
12 {
13 /*------------read the value of the next coin------------*/
14 cout << endl << “enter the value of the next coin:\t”;
15 cin >> coinValue;
16
17 /* compute the total value of the coins deposited so far */
18 totalValue = totalValue + coinValue;
19 }
20
21 /*--- say “thank you” and give the change back to the user */
22 cout << “\n\nThank you for using this soda machine”
23 << “\n\nYour change is:\t” << (totalValue - SODAPRICE);
24 return ( 0 );
25 }
Exercise CS18*
The manager of a store is required to make a deposit of $ 10,000 whenever the sum of the daily sales in
that store is $ 10,000 or more. Write a C++ code segment to read the daily sales in that store, and to
compute their sum until it becomes greater than or equal to $ 10,000. The sum of the daily sales and the
message “it is time to make a deposit” are then printed.
Exercise CS19
A store has 120 bags of coffee and every day, the amount of bags sold is deducted from the current stock
until it becomes less than or equal to 30. The manager of the store must then place a new order.
Write a C++ code segment to read the number of bags 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 bags to purchase
in order to have 120 bags are then printed.
© 2013 Gilbert Ndjatou Page 86
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.
Case Study CS9
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-the-loop until it becomes
greater than 10000.
The loop condition is therefore: power <= 10000.
After Value of
Iteration variable power
- 1
1 1 x 5 = 5
2 5 x 5 = 25
3 25 x 5 = 125
. . .
Variable: power (int) to hold the powers of 5.
©2013 Gilbert Ndjatou Page 87
Algorithm Specification (using a Flowchart)
False True
Figure CS9 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;
}
Start
power = 1
power <= 10000
Power = power * 5
Stop
©2013 Gilbert Ndjatou Page 88
Sentinel-Controlled Iteration
When you want to process a list of values and you do not know how many values are in the list, you
can use a sentinel value (dummy value, flag value, or signal value) to mark the end of the list.
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. With -99, the list could be:
87 69 95 65 73 86 93 68 -99
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:
False True
Read/Access the first data item
data item != sentinel
Process a data item
Read/Access the next data item
Next-Statement
©2013 Gilbert Ndjatou Page 89
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.
Case Study CS10
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.
©2013 Gilbert Ndjatou Page 90
Algorithm Specification (using a Flowchart)
False True
Figure CS10 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 #define COEFICIENT .454
9 #define DUMMYWEIGHT -99.0
10
11 int main()
12 {
13 double pound, // the current weight measurement in Lbs
14
15 cout << fixed << showpoint) << setprecision(2);
16
Start
Read
pound
pound != -99
Read
pound
Write
“Thank you”
Stop
Write
.454 * pound
©2013 Gilbert Ndjatou Page 91
17 /*read the first weight measurement or the dummy value -99.0*/
18 cout << endl
<< “Enter a weight measurement or -99.0 to terminate:\t”;
19 cin >> pound;
20 while (pound != DUMMYWEIGHT)
21 {
22 cout << “\t = ” << (.454 * pound);
23 cout << endl
<< “Enter a weight measurement or -99.0 to terminate:\t”;
24 cin >> pound;
25 }
26 cout << endl << “Thank you”;
27 return (0);
28 }
Exercise CS20*
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;
#defineDUMMYVALUE -99
int main( )
{
int total, value;
cout << “\nEnter all values to add followed by”
<< DUMMYVALUE <<“ to stop\n”;
while ( value != DUMMYVALUE )
{
cin >> value;
total = total + value;
}
cout << endl << “The total of these value is:\t” <<total;
return( 0 );
}
Exercise CS21*
Write a C++ code segment 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 by using the following formula: Celsius = 5.0 / 9 *(Fahrenheit - 32).
Exercise CS22
Write a C++ code segment to read the pay rate and the number of hours of work of one or more
employees and to compute each employee’s gross pay: pay rate * number of hours. The dummy pay
rate -99.00 marks the end of the input values.
©2013 Gilbert Ndjatou Page 92
Exercise CS23
Write a C++ code segment to read the test scores of one or more students (until the sentinel value -99 is
read) and to compute their average.
One-Way Selection using the if Structure
A one-way selection structure is used to specify that the execution of one or more actions be
performed only if a test performed on a condition is true.
It is specified using a flowchart as follows:
False True
C-Statement is one or more statements that specify the operations to be performed when
condition evaluates to true.
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 <Next-Statement>.
condition
C-Statement
Next-Statement
©2013 Gilbert Ndjatou Page 93
Case Study CS11
Problem Statement
A rebate of 5% is given in a store only if the 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.
Variables:
unitPrice ( double ) to hold the unit price.
quantity ( int ) to hold the quantity.
purchase ( double ) to hold the amount of purchase.
Algorithm Specification (using a Flowchart)
False True
Start
Read
unitPrice, quantity
purchase = unitPrice * quantity
purchase >= 100.00
purchase = purchase - .05 * purchase
Write
purchase
Stop
©2013 Gilbert Ndjatou Page 94
Figure CS11 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 }
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>
©2013 Gilbert Ndjatou Page 95
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;
Exercise CS24*
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);
Exercise CS25*
greatt, smallt, and somet are integer variables with initial values. Write a C++ code segment to read an
integer value 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.
Exercise CS26
In a department store, a 10% rebate is given for every purchase of at least $ 20.00. Write a C++ code
segment to read the unit price of a product, the quantity purchased, and to compute the amount of the
purchase after the rebate if applicable.
Exercise CS27
sum, large_ct, middle_ct, and small_ct are integer variables with initial values. Write a C++ code
segment to carry out the following tasks: read a value into the integer variable num. 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.
©2013 Gilbert Ndjatou Page 96
Multiple-Way Selection using if-else Structures
A multiple-way selection structure is used to specify that the action to be performed be chosen from
a list of three or more actions based on the true values of two or more conditions.
A multiple-way selection with four actions and three conditions is specified as follows:
True False
True False
True False
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.
In some situations, Action-4 may also be the null action.
condition1
condition2
condition3
Action-1
Action-2
Action-3 Action-4
Next-Action
©2013 Gilbert Ndjatou Page 97
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.
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>
Case Study CS12
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.
©2013 Gilbert Ndjatou Page 98
Algorithm Specification (using a Flowchart)
True False
True False
True False
True False
Figure CS12 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;
mcode = ‘M’
mcode = ‘S’
mcode = ‘D’
Start
Read
mcode
Write
“married”
Write
“single”
Mcode = ‘W’ Write
“divorced”
Stop
Write
“invalid
”
Write
“Widowed”
©2013 Gilbert Ndjatou Page 99
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 }
Exercise CS28*
A florist who sells four different types of bouquets of flowers has numbered them 101, 202, 303, and
404 with their unit prices specified as follows:
ITEM NUMBER UNIT PRICE
101 $ 5.25
202 $ 3.10
303 $ 9.75
404 $ 6.50
Write a C++ code segment to read an item number and the number of bouquets of that type purchased,
and to compute and print the price of those bouquets.
Exercise CS29
A game consists of selecting a positive integer value and rewarding bonuses to the player according to
the remainder in the division of that number by 5 as follows:
REMAINDER BONUS
0 200
1 350
2 400
3 500
4 750
Write a C++ code segment to read a positive integer value and to output the bonus received by the user.
©2013 Gilbert Ndjatou Page 100
Case Study CS13
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), F (score < 60.00).
It is assumed the input value is a valid test score.
Program Logic
Input: a test score (floating-point value in the range 0.00 to 100.00).
Output: the corresponding letter grade.
Variables: score (double ) to hold a test score.
Algorithm Specification Using a Flowchart
True False
True False
True False
True False
score >= 90.00
score >= 80.00
Score >= 70.00
Start
Read
score
Write
‘A’
Write
‘B’
score >= 60.00 Write
‘C’
Stop
Write
‘F’ Write
‘D’
©2013 Gilbert Ndjatou Page 101
Figure CS13 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.h>
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 }
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’;
©2013 Gilbert Ndjatou Page 102
Exercise CS30*
What is the output of the following program segment for each of the following input values?
a. input value: 3 b. input value: 7 c. input value: 12
cin >> num;
if (num < 5)
cout << "Red\n";
else if (num < 10)
cout << "Yellow\n";
else
cout << "Green\n";
cout << “blue”
Exercise CS31*
The decision table below shows fines imposed for speeding violations. Write a C++ code segment to
read the speed of a car and to output the corresponding fine.
Speed <= 50 mph Fine = $ 0.00
50 < Speed <= 70 Fine = $ 15.00
70 < Speed <= 80 Fine = $ 30.00
Speed > 80 Fine = $ 60.00
Exercise CS32
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 Rebate = $ 2.00
price < $ 20.00 No rebate
A sale tax of 8.25% is also imposed on the price of each purchase (after the rebate, if any).
Write a C++ code segment to read the price of a product and to output the rebate received by the
customer, the price (including the rebate), and the amount due (including taxes).
©2013 Gilbert Ndjatou Page 103
Iterations using the for Structure
The for structure has the following general syntax:
for(<init-expression-list> ; <loop-condition> ; <increment-expression-list>)
{
<body-of-the-loop>
}
It is executed in the same way that the following while structure is executed:
<init-expression-Statements>
while ( <loop-condition> )
{
<body-of-the-loop>
<increment-expression-Statements>
}
Example
1. The following counter-controlled iteration (specified using the while structure) may be specified
using the for structure in any of the following ways in (a), (b), and ( c ):
totalscore = 0;
testcount = 0; // no test score has been read so far
while (testcount < 20) // repeat twenty times
{
cout << “\nEnter a test score please:\t”;
cin >> score;
totalscore + = score;
testcount ++;
}
©2013 Gilbert Ndjatou Page 104
( a )
The <init-expression-list> consists of the expression, testcount = 0,
The <loop-condition> is testcount < 20, and
The <increment-expression-list> consists of the expression, testcount ++ .
totalscore = 0;
for (tescount = 0 ; testcount < 20 ; testcount ++) // repeat twenty times
{
cout << “\nEnter a test score please:\t”;
cin >> score;
totalscore + = score;
}
( b )
Any expression that is evaluated before the <loop condition> is tested for the first time may also be
moved into the <init-expression-list>.
So, we may also specify the expression totalscore = 0 in the <init-expression-list> as follows:
for (totalscore = 0, tescount = 0 ; testcount < 20 ; testcount ++)
{ // repeat twenty times
cout << “\nEnter a test score please:\t”;
cin >> score;
totalscore + = score;
}
( c )
Expressions that are evaluated in the <body-of-the-loop> may be moved into the <increment-
expression-list>.
However, keep in mind that expressions in an expression list are evaluated from left to right.
So, we may move the expression totalscore + = score from the <body-of-the-loop> to the
<increment-expression-list> before the loop increment expression as follows:
©2013 Gilbert Ndjatou Page 105
for (totalscore = 0, tescount = 0 ; testcount < 20 ; totalscore += score, testcount++)
{ // repeat twenty times
cout << “\nEnter a test score please:\t”;
cin >> score;
}
2. The following logically-controlled iteration (specified using the while structure) may be specified
using the for structure in any of the following ways in (a) and (b):
cin >> number;
cout << “\n\nIts digits in reverse order are as follows:\t”;
while (number != 0)
{
cout << (number % 10);
number / = 10;
}
( a )
The <init-expression-list> consists of the expressions,
cin >> number and cout << A\n\nIts digits in reverse order are as follows:\t@.
The <loop-condition> is number != 0, and
The <increment-expression-list> consists of the expression number / = 10.
Each of these components of the structure is written on a separate line for readability.
for(cin >> number , cout << “\n\nIts digits in reverse order are as follows:\t”;
number != 0 ;
number /= 10)
{
cout << (number % 10);
}
©2013 Gilbert Ndjatou Page 106
( b )
The cin and the cout expressions specified in the <init-expression-list> of the for structure in (a)
make it hard to read.
One could improve the readability of the for structure by just leaving the <init-expression-list>
empty as in the following for structure.
Notice that although the <init-expression-list> is empty, the semicolon is still required before the
<loop-condition>.
cin >> number ;
cout << A\n\nIts digits in reverse order are as follows:\t@;
for( ; number != 0 ; number /= 10)
{
cout << (number % 10);
}
for Structures with one or no Statement in the Body- of-the-Loop
The braces may be omitted in a for structure when the <body-of-the-loop> consists of just one
statement.
When the <body-of-the-loop> is empty (that means without any statement), the right parenthesis
must be followed by a semicolon ( ; ).
Example
The following logically-controlled iteration specified using the while structure may be specified
using the for structure in any of the following ways in (a) and (b):
power = 1; // 0th power of 5
while ( power <= 10000) // repeat until a power of 5 is greater than 10000
power * = 5;
©2013 Gilbert Ndjatou Page 107
( a )
The <init-expression-list> consists of the expression, power = 1,
The <loop-condition> is power <= 10000, and
The <increment-expression-list> consists of the expression, power * = 5.
The <body-of-the-loop> is empty.
Notice the semicolon after the right parenthesis. It specifies the null statement. That means to do nothing.
/* Repeat until a power of 5 is greater than 10000 */
for (power = 1 ; power <= 10000 ; power *= 5) ;
( b )
In the above for structure, the expression, power * = 5 could be moved into the <body-of-the-loop>, making the
<increment-expression-list> empty.
Notice that the braces are not required to specify to <body-of-the-loop>, and
Although the <increment-expression-list> is empty, the semicolon is still required after the <loop-condition>.
for (power = 1 ; power <= 10000 ; )
power *= 5; // Repeat until a power of 5 is greater than 1000
Defining Variables in a for Structure
Variables such as the loop iteration counter that are used exclusively in a for structure may be
defined in the <init-expression-list> when they are initialized.
Example
In the following for structure, variable tescount is referenced exclusively in the structure, and could
be defined when it is initialized.
However, the same thing cannot be done for variable totalscore, because it is referenced outside of
the for structure.
©2013 Gilbert Ndjatou Page 108
int totalscore;
for (totalscore = 0, int tescount = 0 ; testcount < 20 ; testcount++)
{
int score; // repeat twenty times
cout << “\nEnter a test score please:\t”;
cin >> score;
totalscore += score;
}
cout << endl << “The sum of the scores is:\t” << totalscore;
Exercise CS33
Rewrite the following program segment as an equivalent segment that uses a for structure:
product = 1;
next = 1;
while (next <= m)
{
product * = next;
next ++ ;
}
Exercise CS34
Rewrite the following program segment as an equivalent segment that uses a while structure:
for(result = 0, count = 1; count < 20; count++)
{
cin >> num;
result += num + 2 * count;
}
©2013 Gilbert Ndjatou Page 109
Iterations using the do/while Structure
Another structure provided in the C/C++ programming language to specify iterations is the do/while
structure.
It has the following syntax:
do
<body-of-the-loop>
while (<condition>);
where <body-of-the-loop> is a single or a compound statement.
Note that the <body-of-the-loop> must contain one or more statements that will eventually make the
loop-condition false.
Also notice the semicolon after the right parenthesis.
Unlike the for structure, the execution of the do/while structure is different from that of the while
structure:
the <body-of-the-loop> is first executed,
then the <condition> is tested;
and the <body-of-the-loop> will continue to be executed as long as the <condition> is true.
It follows that with the do/while structure, the <body-of-the-loop> is executed at least once
Whereas with the while or the for structure, this may not be the case.
Example
Problem 1 write a program to compute the sum of the first ten positive integer values (1, 2, 3, . . . 10).
©2013 Gilbert Ndjatou Page 110
Solution:
#include <iostream>
using namespace std;
#define MAXVALUE 10 /* the maximum value */
int main()
{
int sum = 0 , count;
count = 1;
do
sum += count;
while ( ++ count <= MAXVALUE);
cout << “\nThe sum of the first ten positive integer values is:\t” << sum;
return 0;
}
Problem 2 Write a program to prompt the user to enter Y (for yes) and N (for no). The program will
continuously prompt the user until one of these characters is entered.
Solution:
#include <iostream>
using namespace std;
int main()
{
char answer; // to hold the answer from the user
do
{
cout << “\nEnter Y (for yes) or N (for no):\t”;
cin >> answer;
}
while (answer != ‘Y’ && answer != ‘N’);
cout << “\nThank you”
<< “\nYou did a good job”;
return 0;
}
©2013 Gilbert Ndjatou Page 111
Which Iteration Structure to Use?
Most programmers have a tendency to do the following:
Use the for structure to specify counter-controlled iterations.
Use the while structure to specify logically-controlled iterations.
The do/while structure is rarely used, except for the solution of problems similar to that of Problem
2 in which the <body-of-the-loop> must be executed at least once.
Extra Credit Exercises 1
1. Write a C++ code segment to add the first 20 positive integer values ( 1 + 2 + 3 + . . . + 20) and to
output the result.
2. Write a C++ code segment to read a double precision floating-point value and to calculate and
output its 6th power ( n * n * n * n * n * n).
3. Write a C++ code segment 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.
4. Write a C++ code segment 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.
5. The Fibonacci sequence is the sequence: 1, 1, 2, 3, 5, 8, . . . , such that the first and the second values
are 1, and the value in any position n >= 3 is the sum of the values in the two previous positions: the
value in position 3 is the sum of the values in positions 2 and 1; the value in position 4 is the sum of
the values in positions 3 and 2, . . . etc. Using two integer variables previous1 and previous2 to hold
the values in the two previous positions from the current position, and a variable new to hold the
value in the current position, Write a C++ code segment to read an integer value greater than or
equal to 3, and to output the Fibonacci sequence from position 3 to the position that corresponds to
the value read. For example, if the input value is 8, the output will be: 2, 3, 5, 8, 13, 21.
6. A positive integer value is a prime number if it is divisible only by 1 and by itself. Write a C++ code
segment to read a positive integer value greater than 2 and to output a message indicating whether it
is a prime number or not. To find out whether a positive integer value n greater than 2 is a prime
number, you may repeatedly divide it by i= 2, then 3, then 4, . . . , until the remainder is 0 or
i*i>=n. The given value is a prime number if the remainder is not 0; otherwise, it is not a prime
number.
7. Write a C++ code segment 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. You compute the greatest divisor of an integer value n greater than 1 that is less
than n, by repeatedly dividing 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.
8. Write a C++ code segment 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.
©2013 Gilbert Ndjatou Page 112
9. Write a C++ code segment to read one or more positive integer values and to compute their product.
The sentinel value 0 marks the end of the input values.
10. Write a C++ code segment to read 50 integer values and to determine the number of even values
(among these integer values) and print it.
11. Write a C++ code segment to read one or more integer values and to compute the average of
positive values and print it. If there are no positive values, print an appropriate message.
12. Write a C++ code segment to read an integer value, followed by an operator ( +, -, *, %, or / ), and
then another integer value (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.
13. 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”.
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 >> num2;
2 if(num1 > num2)
3 result = num1 + 4;
4 if (num2 < 7)
5 num1 = num2 + num1;
6 else if (num2 > 10)
7 num1 = 2 * num1;
8 result = result + num1 + num2;
9 cout << result;
©2013 Gilbert Ndjatou Page 113
a. Trace for input value: 8
Line Number Variables
num1 num2 result Output:
- 5 ? 0 13
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 Output:
- 5 ? 0 20
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
Exercise CS35
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;
©2013 Gilbert Ndjatou Page 114
Trace:
Line Number Variables Output:
ndx num result ndx = 6
- 10 ? 0 result = 27
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
Exercise CS36
Trace the execution of each of the following program segments:
a. 1 num = 1; b. 1 ndx = 1;
2 while (num <= 20) 2 pnum = 60;
3 num = num * 2; 3 while(ndx < 5)
4 cout << “\nnum=” << num; {
4 pnum = pnum / ndx;
5 ndx = ndx + 2;
}
6 cout << “\npnum=” << pnum
<< “\nndx=” << ndx;
Exercise CS37
Trace the execution of the following program segment:
Line # 1 int num = 20, result, count;
2 for( result = num, count = 0; count < 3; count++)
3 {
4 num /= 2;
5 result += num + count;
6 }
7 cout << “\nresult=\t” << result << “\nnum=\t” << num;
8 cout << “\ncount=\t” << count;
©2013 Gilbert Ndjatou Page 115
Multiple-Way Selection using the switch Structure
A multiple-way selection structures in which the value of the same expression is tested at each
decision step against an integer or a character value as follows:
if(<expression> = = value-1)
<Statement-1>
else if (<expression> = = value-2)
<Statement-2>
.
.
.
else if (<expression> = = value-n)
<Statement-n>
else
<Default-Statement>
may be specified in C/C++ using the switch structure as follows:
switch(<expression>)
{
case value-1:
<Statement-1>
break;
case value-2:
<Statement-2>
break;
.
.
.
case value-n:
<Statement-n>
break;
default:
<Default-Statement>
}
©2013 Gilbert Ndjatou Page 116
Example 1
Given the following multiple-way selection using if-else Structures
/*------------determine and print the corresponding marital status ------------------------*/
if (mcode == ‘M’)
cout << “\nThis individual is married”;
else if (mcode == ‘S’)
cout << “\nThis individual is single”;
else if (mcode == ‘D’)
cout << “\nThis individual is divorced”;
else if (mcode == ‘W’)
cout << “\nThis individual is a widow”;
else
cout << “\nThe marital code that you have typed is invalid”;
It is specified using the switch structure as follows:
/*------------determine and print the corresponding marital status ------------------------*/
switch(mcode)
{
case ‘M’:
cout << “\nThis individual is married”;
break;
case ‘S’:
cout << “\nThis individual is single”;
break;
case ‘D’:
cout << “\nThis individual is divorced”;
break;
case ‘W’:
cout << “\nThis individual is a widow”;
break;
default:
cout << “\nThe marital code that you have typed is invalid”;
}
©2013 Gilbert Ndjatou Page 117
Example 2 Using the switch Structure without the Default-Statement
Given the following multiple-way selection using if-else structures:
/*------ if the car has a rebate, print it and compute its price with the rebate------------*/
if ( CarType == 2)
{
cout << endl << “This car has a rebate of:\t$” << MIDREBATE;
price = price - MIDREBATE;
}
else if ( CarType == 3)
{
cout << endl << “This car has a rebate of:\t$” << SEDANREBATE;
price = price - SEDANREBATE;
}
else if ( CarType == 5)
{
cout << endl << “This car has a rebate of:\t$” << TRUCKREBATE;
price = price - TRUCKREBATE;
}
It is specified using the switch structure as follows:
/*------ if the car has a rebate, print it and compute its price with the rebate------------*/
switch (CarType)
{
case 2:
cout << endl << “This car has a rebate of:\t$” << MIDREBATE;
price - = MIDREBATE;
break;
case 3:
cout << endl << “This car has a rebate of:\t$” << SEDANREBATE;
price - = SEDANREBATE;
break;
case 5:
cout << endl << “This car has a rebate of:\t$” << TRUCKREBATE;
price - = TRUCKREBATE;
}
Note that the statements specified for each case do not have to be enclosed between the braces.
©2013 Gilbert Ndjatou Page 118
The break Statement and the switch Structure
Example: Role of the break Statement in a switch Structure
Given the following multiple-way selection using the switch structure (specified from line 14 to line 33):
Line Number
1 #include <iostream>
2 using namespace std;
3 int main()
4 {
5 int num, // to hold an integer value
6 bonus; // to hold the bonus earned
7
8 /*----------------read an integer value---------------------*/
9 cout << “\nEnter an integer value:\t”;
10 cin >> num;
11
12 /*--------determine and print the corresponding bonus-------*/
13 bonus = 5;
14 switch(num)
15 {
16 case 2:
17 cout << “\nYou have entered my lucky number”;
18 bonus += 2;
19 break;
20 case 3:
21 case 7:
22 cout << “\nI do not like this number”;
23 - - bonus;
24 break;
25 case 5:
26 cout << “\nIt is OK!”;
27 case 9:
28 cout << “\nYou could do better”;
29 ++ bonus;
30 break;
31 default:
32 cout << “\nGood try”;
33 }
34 cout << “\nYour bonus is:\t” << bonus;
35 return 0;
36 }
©2013 Gilbert Ndjatou Page 119
It is rewritten using if-else structures as follows:
if (num == 2)
{
cout << “\nYou have entered my lucky number”;
bonus += 2;
}
else if (num == 3 || num == 7)
{
cout << “\nI do not like this number”;
- - bonus;
}
else if (num == 5)
{
cout << “\nIt is OK!”;
cout << “\nYou could do better”;
++ bonus; }
else if (num == 9)
{
cout << “\nYou could do better”;
++ bonus; }
else
cout << “\nGood try”;
Exercise CS38
1. Rewrite each of the following code segments using the switch structure.
a. char letter; b. int num, value;
int num = 10; cin >> num;
cin >> letter; if (num + 5 == 0 || num + 5 == -1)
if (letter == ‘A’) value = 10;
{ else if (num + 5 == 2)
cout << endl << “Apple”; value = 7;
num += 5; else if (num + 5 == 5)
} value = 4;
else if (letter == ‘Y’) cout << endl << “value =” << value;
{
cout << endl << “Yellow”;
num ++ ;
}
else if (letter == ‘G’)
cout << endl << “Green”;
else
cout << endl << “Invalid”;
cout << endl << num:
©2013 Gilbert Ndjatou Page 120
2. Rewrite each of the following code segments using if-else structures.
a. int ctl; b. int ctl;
cin >> ctl; cin >> ctl;
switch (ctl) switch (ctl)
{ {
case 0: case 1:
case 1: cout << “red”;
cout << "red "; break;
break; case 2:
case 2: cout << “blue”;
cout << "blue "; case 3:
break; cout << “green”;
case 3: break;
cout << "green "; case 4:
break; cout << “yellow”;
default: }
cout << "yellow";
}
cout << endl << ctl;
3. Provide the output of the program segments in question 2a. for each of the following input values:
i. 1 ii. 2 iii. 3 iv. 4
4. Provide the output of the program segments in question 2b. for each of the following input values:
i. 1 ii. 2 iii. 3 iv. 4
Exercise CS39
A florist sells four different types of bouquets of flowers that he has numbered 101, 202, 303, and 404
with the unit prices specified as follows:
ITEM NUMBER UNIT PRICE
101 $ 5.25
202 $ 3.10
303 $ 9.75
404 $ 6.50
Write a program segment 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 (using the switch structure).
©2013 Gilbert Ndjatou Page 121
Nesting if - else Structures
The following flowchart is specified in C++ as follows:
True False
True False True False
Specification in C++:
if( anum < 1000)
if( bnum < 5 )
(a) result = 1;
else
(c) result = 2;
else
if(bnum > 10 )
(b) result = 3;
else
result = 4;
cout << endl << “result=\t” << result;
if-else structures (a) and (b) are nested inside if-else structure ( c ).
Some examples of the output of this code segment are given as follows:
anum = 500 and bnum = 2 result = 1
anum = 500 and bnum = 12 result = 2
anum = 1200 and bnum = 11 result = 3
anum = 1200 and bnum = 8 result = 4
anum < 1000
bnum < 5 bnum > 10
result = 1 result = 2 result = 3 result = 4
Write result
©2013 Gilbert Ndjatou Page 122
Interpreting Nested if-else Structures
In a nested if-else structure, an else balances the nearest preceding unbalanced if in the same
program block.
Example Interpreting Nested if-else Structures
1.
And its output is specified for each range of values as follows:
Range of Values Output
num > 40 Z W
25 < num <= 40 Y W
15 < num <= 25 X W
num <= 15 W
The above program segment can be rewritten using multiple-way selection as follows:
if (num > 40)
cout << ‘Z’;
else if (num > 25)
cout << ‘Y’;
else if (num > 15)
cout << ‘X’;
cout << “\t W”;
Nested if-else Structures
are Interpreted as Follows
if (num > 15)
if (num > 25)
if (num > 40)
cout << ‘Z’;
else cout << ‘Y’;
else cout << ‘X’;
cout << “\tW”;
if (num > 15)
if (num > 25)
if (num > 40)
cout << ‘Z’;
else
cout << ‘Y’;
else
cout << ‘X’;
else;
cout << “\t W”;
©2013 Gilbert Ndjatou Page 123
2. The following nested if-else structures have different interpretations:
cin >> status >>
value;
if (status == 1)
if (value == 500)
cout << ‘A’;
else
cout << ‘B’;
cout << ‘C’;
cin >> status >> value;
if (status == 1)
{
if (value == 500)
cout << ‘A’;
}
else
cout << ‘B’;
cout << ‘C’;
In the first nested structure, the else balances the second if, whereas in the second, it balances the
first if. The input/output relation is specified as follows:
First Nested if-else Structure Second Nested if-else Structure
Input: status = 1 value = 500 Output: A C Output: A C
Input: status = 1 value != 500 Output: B C Output: C
Input: status != 1 value = 500 Output: C Output: B C
Input: status != 1 value != 500 Output: C Output: B C
Exercise CS40*
1. Provide the output of the program segment specified by the flowchart above for the following
values:
a. anum = 200, bnum = 4; c. anum = 500, bnum = 35
b. anum = 1500, bnum = 17 d. anum = 2000, bnum = 8
2. For each of the following program segments (a) and (b), provide the output for the following input
values:
a. status is 0, and value is 50 c. status is 0, and value is 200
b. status is 1, and value is 50 d. status is 1, and value is 200
©2013 Gilbert Ndjatou Page 124
( a )
cin >> status >> value;
if (status == 0)
if (value < 100)
cout << ‘A’;
else
cout << ‘B’;
cout << ‘C’;
( b )
cin >> status >> value;
if (status == 0)
{
if (value < 100)
cout << ‘A’;
}
else
cout << ‘B’;
cout << ‘C’;
Exercise CS41
1. Use proper indentation to specify the interpretation of the following nested if-else structures:
a. cin >> code >> num1 >> num2; b. if ( num <= 200)
if (code == ‘T’) if ( num < 100)
if (num1 > 100) if ( num <= 0)
{ cout << "A\n";
num++ ; else
num2 * = 5; cout << "B\n";
} else
else cout << "C\n";
num - - ; else
else cout << "D\n";
if ( num2 < 50 )
num1 /= 2;
else
{
num2 += num1;
num1 * = 10;
}
2. For what range of values of the variable num will the output of the program segment 1.b be:
i. A ii. B iii. C iv. D.
3. Rewrite the program segment 1.b using multiple-way selection with if-else structures.
©2013 Gilbert Ndjatou Page 125
Case Study CS13
Problem Statement
The relative risk for individuals to have a certain disease depends on their age and whether they smoke
or not as specified in the following table.
Smoker
Yes No
Age >= 40 6 3
Age < 40 4 1
Write a program to read the age of an individual (integer value) and its smoking status (1 for smoker and
0 for non smoker) and to print its relative risk.
Program Logic
input: the age of an individual and its smoking status (0 or 1).
output: its relative risk to have a certain disease.
variables: age (int) to hold the age of an individual.
status (int) to hold its smoking status.
Algorithm Specification (using a Flowchart)
True False
True False True False
Start
Read
age, status
age >= 40
status = 1 status = 1
Write
6
Write
3
Write
4
Write
1
Stop
©2013 Gilbert Ndjatou Page 126
Figure CS13 Using Nested if-else Structures
Line Number
1 /*************************************************************
2 Program to compute the relative health risk of an individual
3 *************************************************************/
4 #include <iostream>
using namespace std;
5 #define RISK1 6 /* highest risk */
6 #define RISK2 4 /* second highest risk */
7 #define RISK3 3 /* third highest risk */
8 #define RISK4 1 /* lowest risk */
9 #define AGELIMIT 40 /* age limit */
10 #define SMOKER 1 /*smoking status*/
11
12 int main()
13 {
14 int age, //the individual=s age
15 status; //smoking status: 1(smoker) 0 (non smoker)
16
17 /*------read the individual=s age and smoking status ------*/
18 cout << A\nEnter age and smoking status in this order:\t@;
19 cin >> age >> status;
20
21 /*---- determine this individual=s relative health risk ---*/
22 if ( age >= AGELIMIT ) //age is equal or above the age limit
23 if ( status == SMOKER ) // he is a smoker
24 cout << endl << “relative risk is:\t”
25 << RISK1;
26 else // he is a non-smoker
27 cout << endl << “relative risk is:\t”
28 << RISK3;
29 else // he is under the age limit
30 if ( status == SMOKER ) // he is a smoker
31 cout << endl << “relative risk is:\t”
32 << RISK2;
33 else // he is a non-smoker
34 cout << endl << “relative risk is:\t”
35 << RISK4;
36
37 return 0;
38 }
©2013 Gilbert Ndjatou Page 127
Case Study CS14
Problem Statement
The simple interest rate on loans at a local bank depends on the client’s account balance and the amount
of the loan as follows:
Amount Borrowed
< $ 750.00 >= $ 750.00
Balance < $ 5000.00 9 % 8 %
--------------------------------------------------------------------------------------------------
< $ 1000.00 >= $ 1000.00
Balance >= $ 5000.00 5 % 4 %
Write a program to read a client’s account balance and the amount of the loan, and to compute the
simple interest and print it.
Program Logic
Input: a client’s balance, and the amount of the loan.
Output: the simple interest on the loan.
Variables:
balance (double) to hold the account balance.
amount(double) to hold the loan amount.
rate (double) to hold the simple interest rate.
Algorithm Specification (using a Flowchart)
True False
True False True False
Start
Read
balance, amount
status
balance < 5000
amount < 1000 amount < 750
Stop
rate = .09 rate = .08 rate = .05 rate = .04
Write
rate * amount
©2013 Gilbert Ndjatou Page 128
Figure CS14 Using Nested if-else Structures
Line Number
1 /**************************************************************
2 Program to compute the simple interest on a loan
3 **************************************************************/
4 #include <iostream>
5 using namespace std;
6 int main( )
7 {
8 double balance, // the account balance
9 amount, // the amount borrowed
10 rate; // the interest rate
11
12 /*----------read the balance and the amount of loan --------*/
13 cout << endl << AEnter the balance and amount of loan :\t@;
14 cin >> balance >> amount;
15
16 /*---------------- get the interest rate ------------ ------*/
17 if (balance < 5000.00)
18 if (amount < 750.00)
19 rate = .09;
20 else
21 rate = .08;
22 else
23 if (amount < 1000.00)
24 rate = .05;
25 else
26 rate = .04;
27
28 /*---------- compute and print the simple interest ---------*/
29 cout << endl << “The interest is:\t” << (rate * amount);
30
31 return 0;
32 }
Exercise CS42
The contribution fees of the members of a club depend on whether they are students or not, and whether
it is a family membership or a single membership as follows:
Famil membership
Yes No
Student $ 30.00 $ 25.00
Non-Student $ 150.00 $ 100.00
Assuming that the status of a member is encoded by an integer value (1 for student, and 0 for non-
student) and that the type of membership is also encoded by an integer value (1 for family, and 0 for
non-family membership), write a program segment to read the status of a member and its type of
membership, and to output its membership fees.
©2013 Gilbert Ndjatou Page 129
Nested Iterations
Case Study CS15
Problem Statement 15 salesmen have reported their total sales (in dollars) in 10 different cities as follows:
Cities #
salesman # 1 2 3 . . . 10
1 7000.00 4000.00 6000.00 . . . 7000.00
2 4000.00 5000.00 1000.00 . . . 500.00
. .
. .
. .
15 2000.00 7000.00 4000.00 . . . 2000.00
Write a program segment to read the total sales of each salesman in all 10 cities, and to compute and
print their sum. Your program must also compute the sum of the total sales for the company. That
means, the sum of the total sales of the 15 salesmen in the 10 cities.
Program Logic
Input: the total sales in 10 cities for 15 salesmen.
Output: each salesman’s sum of total sales, and the company’s total sales.
The algorithm consists of repeating the following steps 15 times:
1. Read a salesman’s total sales in the 10 cities and compute their sum.
2. Add this salesman’s sum of the cities total sales to the company’s total sale.
3. Print this salesman’s sum of the cities total sales.
We therefore have here a counter-controlled iteration: we need a counter (let’s call it scount) to
count the salesmen: its initial value is 0, and its final value is 15.
We need a variable to hold the sum of the total sales of a salesman in all ten cities (let’s call it
salesmanTotal).
To compute the sum of the total sales for the company, we need a variable (running total) that is first
initialized to 0 (outside of the body-of-the-loop) and then incremented by the sum of the total sales
in all ten cities for each salesman (salesmanTotal). Let’s call this variable companyTotal.
Step 1 says to read the total sales for a salesman in the 10 cities and compute their sum. This is done
by repeating the following steps 10 times:
1.1 Read a salesman’s total sales in a city and add it to the variable salesmanTotal.
We therefore have here a counter-controlled iteration: we need a counter (let’s call it cityCount) to
count the cities (initial value 0, and final value 10)
©2013 Gilbert Ndjatou Page 130
We also need a variable to hold a salesman’s total sales in a city (let’s call it citySale).
The algorithm follows:
Variables:
companyTotal (double) to hold the total sales in the company.
scount (int) to count the salesmen.
salesmanTotal (double) to hold a salesman’s total sales (in all the cities).
citySale (double) to hold a salesman’s total sales in a city.
cityCount (int) to count the cities.
Figure CS15 Using Nested Iterations
Line Number
1 /****************************************************************
2 Program to process salesmen’s total sales in a company
3 ****************************************************************/
4 #include <iostream.h>
5 #define CITYMAX 10 /* maximum number of cities */
6 #define SALESMENMAX 15 /* maximum number of salesmen */
7
8 int main()
9 {
10
11 /*---compute the total sales of the company and print it----*/
12 double companyTotal = 0; //the total sales of the company
13 for ( int scount = 0; scount < SALESMENMAX ; scount ++ )
14 {
15 /*-- compute a salesman’s sum of total sales and print it -*/
16 double salesmanTotal = 0; // the sum of a salesman’s total sale
17 cout << “\nEnter the total sales of salesman #” << (scount + 1)
18 << “ in all cities, followed by the ENTER key” << endl;
19 for ( int cityCount = 0 ; cityCount < CITYMAX ; cityCount ++ )
20 {
21 /*-- read the total sales in this city for this salesman and add it to its total*/
22 double citySale; //a salesman’s total sale in a city
23 cin >> citySale;
24 salesmanTotal += citySale;
25 }
26 cout << “\nThe sum of total sales for salesman # “
27 << (scount + 1) << “is:\t” << salesmanTotal;
28
29 /*-add salesman’s sum of total sales to the company total*/
30 companyTotal += salesmanTotal;
31 }
32
33 /*---------- output the company total sales ----------------*/
34 cout << “\nThe company total sales is:\t” << companyTotal;
35 return 0;
36 }
©2013 Gilbert Ndjatou Page 131
Exercise CS43
Each student in a class of 20 students has completed 6 quizzes and has received a score on each of these
quizzes. The quizzes are numbered from 1 to 6, and students are numbered from 1 to 20 as follows:
Quiz #
1 2 3 4 5 6
Student #
1 95.0 80.0 90.0 86.0 97.0 98.0
2 87.0 78.0 79.0 80.0 80.0 83.0
. .
. .
. .
20 78.0 89.0 76.0 88.0 78.0 92.0
Write a program segment to read each student’s quiz scores, and to compute his/her average quiz
score and print it. The program must also compute the class average of the quizzes. The class
average is the sum of all students’ average scores divided by 20.
Exercise CS44
The 9x9 multiplication table of the digits 1 to 9 is produced by multiplying the row number by the
column number as follows:
Column #
1 2 3 4 5 6 7 8 9
Row #
1 1 x 1 1 x 2 1 x 3 1 x 4 . . . 1 x 9
2 2 x 1 2 x 2 2 x 3 2 x 4 . . . 2 x 9
. .
. .
. .
9 9 x 1 9 x 2 9 x 3 9 x 4 . . . 9 x 9
Write a program segment to generate the above multiplication table.
©2013 Gilbert Ndjatou Page 132
Extra Credit Exercises 2
1. Write a program segment to read an integer value, an operator ( +, -, *, %, or /), and another integer
value in this order (for example, 23 + 5), 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 (using the
switch structure). Note that in the division of the first value by the second, you must make sure that
the second value is not zero.
2. A game consists of reading a positive integer value and rewarding bonuses based on the remainder in
the division of that number by 5 as follows: 0: 200; 1: 350; 2: 400; 3: 500; 4: 750.
Write a program segment to read a positive integer value, and to output the bonus awarded to the
user (using the switch structure).
3. A travel agency rewards bonuses to its clients based on the price of the vacation package and the
number of people in the vacation group as follows:
Number of people
< 3 3 > 3
Price <= $ 2500.00 $ 20.00 $ 10.00 $ 5.00
Price > $ 2500.00 $ 50.00 $ 25.00 $ 15.00
Write a program segment to read the price of a vacation package and the number of people in the
vacation group, and to output the bonus awarded.
4. Rewrite the code segment in Exercise CS43 by assuming that each student has completed one or
more quizzes. For each student, the dummy score of -99 is entered to end his/her list of scores. A
student’s average score is the sum of the scores on the quizzes divided by the number of quizzes
completed.
5. Trace the execution of the following program segment and show its output:
Line Number
1 int row, column;
2 row = 10;
3 while( row > 5)
4 {
5 cout << endl << row;
6 column = 1;
7 while (column < 5)
8 {
9 cout << ‘\t’ << row + column;
10 column ++ ;
11 }
12 row - = 2;
13 }
©2013 Gilbert Ndjatou Page 133
Solutions of the Exercises
Exercise CS1*
a) num1 >= 5 || num2 + 3 == num3 d) num2 + 3 == num3 * 4 || ch >= ‘Z’
5 >= 5 || 7 + 3 == 2 * 4 || ‘K’ >= ‘Z’
True 10 == 8 || False
True False || False
False False
b) ‘A’ <= ch && fnum + 7.2 != 2.5 e) num1 < 3 && num2 > num3
‘A’ <= ‘K’ && 11.75 + 7.2 != 2.5 5 < 3 &&
True && 18.95 != 2.5 False
True && True False
True
c) !(3 * num1 + 4 < num3 * 2) f) !(fnum * 2 < num1 + 20)
!( 3 * 5 + 4 < 2 * 2) !(11.75 * 2 < 5 + 20)
!( 19 < 4) !( 23.50 < 25)
! False !True
True False
Exercise CS6*
a) cin >> num;
if (num = 5) ---------------------> num == 5
sum = num + 4;
else
sum = num + 10;
b) cin >> num;
if (num > 5 && <= 10) ---------------> num > 5 && num <= 10
cout << num + 15;
else
cout << num - 3;
c) cin >> num; cin >> num;
if (num < 15) if (num < 15)
result1 = 2 * num; ----------------> {
result2 = num + 20; result = 2 * num;
else ---------------- > result2 = num + 20;
result1 = 5 * num; }
result = result1 + result2; else
cout << “\nThe result is:\t” << result; reult1 = 5 * num;
result = result1 + result2;
cout << “\nThe result is:\t” << result;
©2013 Gilbert Ndjatou Page 134
Exercise CS7*
Program trace
Input: 4 input: 20
Line # num Line # num
1 4 1 20
2 4 2 20
3 10 5 20
4 10 6 20
6 10
Output: num = 10 Output: num / 4 = 5
result = 20 result = 40
Exercise CS10*
a. b. c.
count = 0; count = 0;
while( count < 10 ) while(count < 10) count = 0;
{ { while(count < 10 )
cin >> num; count = 0; {
cout << 2 * num; cin >> num; cin >> num;
count = count + 1; cout << 2 * num; cout << 2 * num;
} count = count + 1; count = count + 1;
} }
Exercise CS12*
a. b.
sum = 0; sum = 0;
count = 0; count = 0;
while (count < 10 ) while (count < 10 )
{ {
sum = 0; cin>>num;
cin >> num; sum = sum + num;
sum = sum + num; count = count + 1;
count = count + 1; }
}
Exercise CS13*
Variables
testCount (int) to count the test scores
score (double) to hold a test score
totalScore (double) to hold the current total of the test scores
©2013 Gilbert Ndjatou Page 135
C++ Language Code Segment
int testCount = 0; // to count the test scores
double score, // to hold a test score
totalScore = 0; // to hold the current total of the test scores
while ( testCount < 20 )
{
cout << endl << “enter a test score:\t” ;
cin >> score;
totalScore = totalScore + score;
testCount = testCount + 1;
}
cout << endl << “the average test score is:\t” << totalScore / 20;
Flowchart
False True
Start
totalScore = totalScore + score
testCount < 20
Stop
testCount = 0
Read
score
totalScore = 0
testCount = testCount + 1
Write
totalScore / 20
©2013 Gilbert Ndjatou Page 136
Exercise CS18*
Variables
totalSale (double) to hold the total sale in the store
dailySale (double) to hold a daily sale in the store
Flowchart
False True
C++ Language Code Segment
int totalSale = 0, // to hold the total sale in the store
dailySale; // to hold a daily sale in the store
while (totalSale < 10000)
{
cin >> dailySale;
totalSale + = dailySale;
}
cout << endl << totalSale - 10000 << “\tIt is time to make a deposit”;
Start
totalSale = totalSale + dailySale
totalSale < 10000
Stop
totalSale = 0
Read
dailySale
Write
totalSale - 10000
“time to make deposit”
©2013 Gilbert Ndjatou Page 137
Exercise CS20*
#define DUMMYVALUE -99
int main ( )
{
int total = 0, value;
cout << “\nEnter all values to add followed by”
<< DUMMYVALUE << “to stop\n”;
cin >> value; // add this statement here
while ( value != DUMMYVALUE )
{
cin >> value; // remove this statement
total = total + value;
cin >> value; // add this statement here
}
cout << endl << “The total of these values is:\t” << total;
return ( 0 );
}
Exercise CS21*
Variables Ftemp (double) to hold a temperature in Fahrenheit
Flowchart
False True
C++ Language Code Segment
double Ftemp; // to hold a temperature in Fahrenheit
cin >> Ftemp;
while (Ftemp != -99.00)
{
cout << endl << Ftemp << “\t” << 5.0 / 9 * (Ftemp – 32);
cin >> Ftemp;
}
Start
Ftemp != -99.00
Stop Read
Ftemp
Write
5.0 / 9 * (Ftemp – 32)
Read
Ftemp
©2013 Gilbert Ndjatou Page 138
Exercise CS24*
a. Input value: 4 b. Input Value: 20
Output Output
Result= 3 pnum= 27
Result= 19
Exercise CS25*
Variable num (int) to hold the integer value
Flowchart
False True
False True
Start
Read
num
num < 5
num > 20
greatt = greatt+ 2
somet = somet + 7
Stop
smallt = smallt + 1
smallt = smallt - 3
©2013 Gilbert Ndjatou Page 139
C++ Language Code Segment
int num; // to hold the integer value
cin >> num;
if (num < 5)
smallt = smalt + 1;
if (num > 20)
greatt = greatt + 2;
else
smallt = smallt – 3;
somet = somet + 7;
Exercise CS28*
Variables
num (int) to hold a bouquet type code.
unprice (double) to hold its unit price.
qty (int) to hold its quantity.
C++ Language Code Segment
int num, // to hold a bouquet type code
qty; // to hold its quantity
double uprice; // to hold its unit price
cin >> num >> qty;
if (num = = 101)
uprice = 5.25;
else if (num = = 202)
uprice = 3.10;
else if (num = = 303)
uprice = 9.75;
else if (num = = 404)
uprice = 6.50;
else
uprice = 0.0;
cout << endl << “The price is:\t” << (uprice * qty);
if (uprice = = 0)
cout << endl << “invalid bouquet number”;
©2013 Gilbert Ndjatou Page 140
Flowchart
True False
True False
True False
True false
True False
Start
Read
num, qty
num = 101
uprice = 5.25
uprice = 3.10
num = 202
num = 303
uprice = 9.75
uprice = 0.0 uprice = 6.50
num = 404
Write
uprice * qty
Stop
uprice = 0
Write
“invalid bouquet number”
©2013 Gilbert Ndjatou Page 141
Exercise CS30*
a. Input value: 3 b. Input value: 7 c. Input value: 12
Output Output Output
Red Yellow Green
blue blue blue
Exercise CS31*
Variables
speed (int) to hold the speed of the car.
fine (double) to hold the fine
Flowchart
True False
True False
True False
speed <= 50.00
fine = 0.00
fine = 15.00
speed <= 70.00
speed <= 80.00
fine = 30.00 fine = 60.00
Write
fine
Stop
Start
Read
speed
©2013 Gilbert Ndjatou Page 142
C++ Language Code Segment
int speed; // to hold the speed of the car
double fine; // to hold the fine
cin >> speed;
if (speed <= 50)
fine = 0.00;
else if (speed <= 70)
fine = 15.00;
else if (speed <= 80)
fine = 30.00;
else
fine = 60.00;
cout << endl << “the fine imposed is:\t” << fine;