Manual Del Instructorcap 4
Manual Del Instructorcap 4
Self-Review Exercises
4.1 Answer each of the following questions.
a) All programs can be written in terms of three types of control statements: ,
and .
ANS: Sequence, selection and iteration.
b) The selection statement is used to execute one action when a condition is true
or a different action when that condition is false.
ANS: if…else.
c) Repeating a set of instructions a specific number of times is called iteration.
ANS: Counter-controlled or definite.
d) When it isn’t known in advance how many times a set of statements will be repeated,
a(n) value can be used to terminate the iteration.
ANS: Sentinel, signal, flag or dummy.
4.2 Write four different C++ statements that each add 1 to integer variable x.
ANS: x = x + 1;
x += 1;
++x;
x++;
Self-Review Exercises 3
4.5 Combine the statements that you wrote in Exercise 4.4 into a program that calculates and
prints the sum of the integers from 1 to 10. Use the while statement to loop through the calculation
and increment statements. The loop should terminate when the value of x becomes 11.
ANS: See the following code:
4.6 State the values of each of these unsigned int variables after the calculation is performed.
Assume that, when each statement begins executing, all variables have the integer value 5.
a) product *= x++;
ANS: product = 25, x = 6;
=
b) quotient /= ++x;
ANS: quotient = 0, x = 6;
4.7 Write single C++ statements or portions of statements that do the following:
a) Input unsigned int variable x with cin and >>.
ANS: cin >> x;
b) Input unsigned int variable y with cin and >>.
ANS: cin >> y;
c) Declare unsigned int variable i and initialize it to 1.
ANS: unsigned int i{1};
d) Declare unsigned int variable power and initialize it to 1.
ANS: unsigned int power{1};
e) Multiply variable power by x and assign the result to power.
ANS: power *= x;
or
power = power * x;
f) Preincrement variable i by 1.
ANS: ++i;
g) Determine whether i is less than or equal to y.
ANS: if (i <= y)
h) Output integer variable power with cout and <<.
ANS: cout << power << endl;
cpphtp10_04.FM Page 4 Tuesday, August 2, 2016 11:11 AM
4.8 Write a C++ program that uses the statements in Exercise 4.7 to calculate x raised to the y
power. The program should have a while iteration statement.
ANS: See the following code:
Exercises 5
while (z >= 0) {
sum += z;
}
ANS: The value of the variable z is never changed in the while statement. Therefore, if the
loop-continuation condition (z >= 0) is initially true, an infinite loop is created. To
prevent the infinite loop, z must be decremented so that it eventually becomes less
than 0.
Exercises
4.11 (Correct the Code Errors) Identify and correct the error(s) in each of the following:
a) if (age >= 65); {
cout << "Age is greater than or equal to 65" << endl;
}
else {
cout << "Age is less than 65 << endl";
}
ANS: The semicolon at the end of the if condition should be removed. The closing double
quote after the second endl should be placed after 65.
b) if (age >= 65) {
cout << "Age is greater than or equal to 65" << endl;
else; {
cout << "Age is less than 65 << endl";
}
ANS: The semicolon after the else should be removed. The closing double quote after the
second endl should be placed after 65.
c) unsigned int x{1};
unsigned int total;
4
5 int main() {
6 unsigned int x{1};
7 unsigned int total{0};
8
9 while (x <= 10) {
10 int y = x * x;
11 cout << y << endl;
12 total += y;
13 ++x;
14 }
15
16 cout << "Total is " << total << endl;
17 }
ANS:
Top:
Determine the current and combined miles/gallon for each trip
First refinement:
Initialize variables
For each trip, input the miles driven and gallons used, then calculate and print the
miles/gallon for that trip
Calculate and print the overall average miles/gallon
Second refinement:
Initialize totalGallons to zero
cpphtp10_04.FM Page 7 Tuesday, August 2, 2016 11:11 AM
Exercises 7
ANS:
Top:
cpphtp10_04.FM Page 8 Tuesday, August 2, 2016 11:11 AM
Exercises 9
First refinement:
Input customer’s data
For each customer, calculate and display the customer’s new balance, and display a
message if user’s balance exceeds credit limit
Process next customer
Second refinement:
Prompt the user for the first customer’s account number
Input the first customer’s account number
While the sentinel value (-1) has not been entered for the account number
Prompt the user for the customer’s beginning balance
Input the customer’s beginning balance
Prompt the user for the customer’s total charges
Input the customer’s total charges
Prompt the user for the customer’s total credits
Input the customer’s total credits
Prompt the user for the customer’s credit limit
Input the customer’s credit limit
Calculate and display the customer’s new balance
If the balance exceeds the credit limit
Print the account number
Print the credit limit
Print the balance
Print “Credit Limit Exceeded”
Input the next customer’s account number
4.15 (Sales-Commission Calculator) A large company pays its salespeople on a commission basis.
The salespeople each receive $200 per week plus 9% of their gross sales for that week. For example,
a salesperson who sells $5000 worth of chemicals in a week receives $200 plus 9% of $5000, or a
total of $650. Develop a C++ program that uses a while statement to input each salesperson’s gross
sales for last week and calculates and displays that salesperson’s earnings. Process one salesperson’s
figures at a time.
ANS:
Top:
cpphtp10_04.FM Page 10 Tuesday, August 2, 2016 11:11 AM
For an arbitrary number of salespeople, determine each salesperson’s earnings for the
previous week
First refinement:
For each salesperson
Input the salesperson’s sales for the week
Calculate and print the salesperson’s wages for the week
Second refinement:
Prompt the user for the first salesperson’s sales in dollars
Input the first salesperson’s sales in dollars
While the sentinel value (-1) has not been entered for the sales
Calculate the salesperson’s wages for the week as 200 dollars added to 9 percent of
the salesperson’s sales (calculated by multiplying the sales with .09)
Print the salesperson’s wages for the week
Prompt the user for the next salesperson’s sales in dollars
Input the next salesperson’s sales in dollars
4.16 (Salary Calculator) Develop a C++ program that uses a while statement to determine the
gross pay for each of several employees. The company pays “straight time” for the first 40 hours
worked by each employee and pays “time-and-a-half” for all hours worked in excess of 40 hours.
You are given a list of the employees of the company, the number of hours each employee worked
last week and the hourly rate of each employee. Your program should input this information for
each employee and should determine and display the employee’s gross pay.
ANS:
Top:
Determine the gross pay for an arbitrary number of employees
First refinement:
For each employee
Input the hours worked
Input the hourly rate
Calculate and display worker’s gross pay
Second refinement:
Prompt the user for the hours worked for the first employee
cpphtp10_04.FM Page 11 Tuesday, August 2, 2016 11:11 AM
Exercises 11
ANS:
****
++++++++
****
++++++++
****
++++++++
****
++++++++
****
++++++++
4.22 (What Does this Program Do?) What does the following program print?
ANS:
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
4.23 (Dangling-else Problem) C++ compilers always associate an else with the immediately
preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can
lead to what is referred to as the dangling-else problem. The indentation of the nested statement
if (x > 5)
if (y > 5)
cout << "x and y are > 5";
else
cout << "x is <= 5";
appears to indicate that if x is greater than 5, the nested if statement determines whether y is also
greater than 5. If so, the statement outputs the string "x and y are > 5". Otherwise, it appears that
if x is not greater than 5, the else part of the if…else outputs the string "x is <= 5". Beware! This
nested if…else statement does not execute as it appears. The compiler actually interprets the
statement as
if (x > 5)
if (y > 5)
cout << "x and y are > 5";
else
cout << "x is <= 5";
in which the body of the first if is a nested if…else. The outer if statement tests whether x is
greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second
condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second con-
dition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.
Equally bad, if the outer if statement’s condition is false, the inner if…else is skipped and noth-
ing is displayed. For this exercise, add braces to the preceding code snippet to force the nested
if…else statement to execute as it was originally intended.
ANS:
cpphtp10_04.FM Page 13 Tuesday, August 2, 2016 11:11 AM
Exercises 13
if (x > 5) {
if (y > 5) {
cout << "x and y are > 5";
}
}
else {
cout << "x is <= 5";
}
@@@@@
$$$$$
&&&&&
ANS: if (y == 8) {
if (x == 5) {
cout << "@@@@@" << endl;
}
else {
cout << "#####" << endl;
}
}
ANS: if (y == 8) {
if (x == 5) {
cout << "@@@@@" << endl;
}
else {
cout << "#####" << endl;
cout << "$$$$$" << endl;
cout << "&&&&&" << endl;
}
}
ANS: if (y == 8) {
if (x == 5) {
cout << "@@@@@" << endl;
}
else {
cout << "#####" << endl;
cout << "$$$$$" << endl;
}
}
d) Assuming x = 5 and y = 7, the following output is produced. [Note: The last three out-
put statements after the else are all part of a block.]
cpphtp10_04.FM Page 15 Tuesday, August 2, 2016 11:11 AM
Exercises 15
#####
$$$$$
&&&&&
ANS: if (y == 8) {
if (x == 5) {
cout << "@@@@@" << endl;
}
}
else {
cout << "#####" << endl;
cout << "$$$$$" << endl;
cout << "&&&&&" << endl;
}
4.32 What’s wrong with the following statement? Provide the correct statement to accomplish
what the programmer was probably trying to do.
cout << ++(x + y);
ANS: The ++ operator must be used in conjunction with variables. The programmer prob-
ably intended to write the statement: cout << x + y + 1;.
cpphtp10_04.FM Page 16 Tuesday, August 2, 2016 11:11 AM