You are on page 1of 47

Solution Manual for C++ How to Program: Late

Objects Version, 7/E 7th Edition Paul Deitel, Harvey


Deitel

To download the complete and accurate content document, go to:


https://testbankbell.com/download/solution-manual-for-c-how-to-program-late-objects-
version-7-e-7th-edition-paul-deitel-harvey-deitel/
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition Paul Deitel, H

Control Statements, Part 2:


Solutions 4
Not everything that can be
counted counts, and not every
thing that counts can be
counted.
—Albert Einstein

Who can control his fate?


—William Shakespeare

The used key is always bright.


—Benjamin Franklin

Intelligence … is the faculty of


making artificial objects,
especially tools to make tools.
—Henri Bergson

Objectives
In this chapter you’ll learn:
■ The essentials of counter-
controlled repetition.
■ To use for and do…while
to execute statements in a
program repeatedly.
■ To implement multiple
selection using the switch
selection statement.
■ How break and continue
alter the flow of control.
■ To use the logical operators
to form complex conditional
expressions in control
statements.
■ To avoid the consequences of
confusing the equality and
assignment operators.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Visit TestBankBell.com to get complete for all chapters


70 Chapter 4 Control Statements, Part 2: Solutions

Answers to Self-Review Exercises


4.1 State whether the following are true or false. If the answer is false, explain why.
a) The default case is required in the switch selection statement.
ANS: False. The default case is optional. Nevertheless, it is considered good software en-
gineering to always provide a default case.
b) The break statement is required in the default case of a switch selection statement to
exit the switch properly.
ANS: False. The break statement is used to exit the switch statement. The break statement
is not required in the default case when it is the last case. Nor will the break state-
ment be required if having control proceed with the next case makes sense.
c) The expression ( x > y && a < b ) is true if either the expression x > y is true or the
expression a < b is true.
ANS: False. When using the && operator, both of the relational expressions must be true
for the entire expression to be true.
d) An expression containing the || operator is true if either or both of its operands are
true.
ANS: True.
4.2 Write a C++ statement or a set of C++ statements to accomplish each of the following:
a) Sum the odd integers between 1 and 99 using a for statement. Assume the integer vari-
ables sum and count have been declared.
ANS: sum = 0;
for ( count = 1; count <= 99; count += 2 )
sum += count;
b) Print the value 333.546372 in a 15-character field with precisions of 1, 2 and 3. Print each
number on the same line. Left-justify each number in its field. What three values print?
ANS: cout << fixed << left
<< setprecision( 1 ) << setw( 15 ) << 333.546372
<< setprecision( 2 ) << setw( 15 ) << 333.546372
<< setprecision( 3 ) << setw( 15 ) << 333.546372
<< endl;
Output is:
333.5 333.55 333.546
c) Calculate the value of 2.5 raised to the power 3 using function pow. Print the result with
a precision of 2 in a field width of 10 positions. What prints?
ANS: cout << fixed << setprecision( 2 )
<< setw( 10 ) << pow( 2.5, 3 )
<< endl;
Output is:
15.63
d) Print the integers from 1 to 20 using a while loop and the counter variable x. Assume
that the variable x has been declared, but not initialized. Print only 5 integers per line.
[Hint: When x % 5 is 0, print a newline character; otherwise, print a tab character.]
ANS: x = 1;
while ( x <= 20 )
{
if ( x % 5 == 0 )
cout << x << endl;
else
cout << x << '\t';

x++;
}

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 71

e) Repeat Exercise 4.2(d) using a for statement.


ANS: for ( x = 1; x <= 20; x++ )
{
if ( x % 5 == 0 )
cout << x << endl;
else
cout << x << '\t';
}

4.3 Find the errors in each of the following code segments and explain how to correct them.
a) x = 1;
while ( x <= 10 );
x++;
}
ANS: Error: The semicolon after the while header causes an infinite loop.
Correction: Replace the semicolon by a {, or remove both the ; and the }.
b) for ( y = .1; y != 1.0; y += .1 )
cout << y << endl;
b) Error: Using a floating-point number to control a for repetition statement.
Correction: Use an int and perform the proper calculation to get the values you desire.
for ( y = 1; y != 10; y++ )
cout << ( static_cast< double >( y ) / 10 ) << endl;

c) switch ( n )
{
case 1:
cout << "The number is 1" << endl;
case 2:
cout << "The number is 2" << endl;
break;
default:
cout << "The number is not 1 or 2" << endl;
break;
}
c) Error: Missing break statement in the first case.
Correction: Add a break statement at the end of the first case. This is not an error if you
want the statement of case 2: to execute every time the case 1: statement executes.
d) The following code should print the values 1 to 10.
n = 1;
while ( n < 10 )
cout << n++ << endl;
ANS: Error: Improper relational operator used in the loop-continuation condition.
Correction: Use <= rather than <, or change 10 to 11.

Exercises
4.4 Find the error(s), if any, in each of the following:
a) For ( x = 100, x >= 1, x++ )
cout << x << endl;
ANS: For should be for. The commas should be semicolons. The ++ should be a decre-
ment such as --.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
72 Chapter 4 Control Statements, Part 2: Solutions

b) The following code should print whether integer value is odd or even:
switch ( value % 2 )
{
case 0:
cout << "Even integer" << endl;
case 1:
cout << "Odd integer" << endl;
}

ANS: case 0 needs a break statement.


c) The following code should output the odd integers from 19 to 1:
for ( x = 19; x >= 1; x += 2 )
cout << x << endl;

ANS: += should be -=.


d) The following code should output the even integers from 2 to 100:
counter = 2;

do
{
cout << counter << endl;
counter += 2;
} While ( counter < 100 );

ANS: While should be while. Operator < should be <=.


4.5 (Summing Integers) Write a program that uses a for statement to sum a sequence of inte-
gers. Assume that the first integer read specifies the number of values remaining to be entered. Your
program should read only one value per input statement. A typical input sequence might be
5 100 200 300 400 500

where the 5 indicates that the subsequent 5 values are to be summed.


ANS:

1 // Exercise 4.5 Solution: ex04_05.cpp


2 // Total a sequence of integers.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int total = 0; // current total
9 int number; // number of values
10 int value; // current value
11
12 // display prompt
13 cout << "Enter the number of values to be summed "
14 << "followed by the values: \n";
15 cin >> number; // input number of values
16
17 // loop number times
18 for ( int i = 1; i <= number; i++ )
19 {

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 73

20 cin >> value;


21 total += value;
22 } // end for
23
24 // display total
25 cout << "Sum of the " << number << " values is " << total << endl;
26 } // end main

Enter the number of values to be summed followed by the values:


5 100 200 300 400 500
Sum of the 5 values is 1500

4.6 (Averaging Integers) Write a program that uses a for statement to calculate and print the
average of several integers. Assume the last value read is the sentinel 9999. A typical input sequence
might be
10 8 11 7 9 9999

indicating that the program should calculate the average of all the values preceding 9999.
ANS:

1 // Exercise 4.6 Solution: ex04_06.cpp


2 // Average a sequence of integers.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int value; // current value
9 int count = 0; // number of inputs
10 int total = 0; // sum of inputs
11
12 // prompt for input
13 cout << "Enter integers (9999 to end):" << endl;
14 cin >> value;
15
16 // loop until sentinel value read from user
17 while ( value != 9999 )
18 {
19 total += value; // update sum
20 count++; // update number of inputs
21
22 cin >> value; // read in next value
23 } // end while
24
25 // if user entered at least one value
26 if ( count != 0 )
27 cout << "\nThe average is: "
28 << static_cast< double > ( total ) / count << endl;
29 else
30 cout << "\nNo values were entered." << endl;
31 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
74 Chapter 4 Control Statements, Part 2: Solutions

Enter integers (9999 to end):


10 8 11 7 9 9999

The average is: 9

4.7 What does the following program do?

1 // Exercise 4.7: ex04_07.cpp


2 // What does this program print?
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int x; // declare x
9 int y; // declare y
10
11 // prompt user for input
12 cout << "Enter two integers in the range 1-20: ";
13 cin >> x >> y; // read values for x and y
14
15 for ( int i = 1; i <= y; i++ ) // count from 1 to y
16 {
17 for ( int j = 1; j <= x; j++ ) // count from 1 to x
18 cout << '@'; // output @
19
20 cout << endl; // begin new line
21 } // end outer for
22 } // end main

ANS:
Ouput:

Enter two integers in the range 1-20: 7 15


@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 75

Explanation:
This program uses the first number input by the user as the number of @ symbols to output per line
and uses the second number input by the user as the number of lines to output. Those values are
used in a nested for statement in which the outer for statement controls the number of lines of
output and the inner for statement displays each line of output.
4.8 (Find the Smallest Integer) Write a program that uses a for statement to find the smallest
of several integers. Assume that the first value read specifies the number of values remaining.
ANS:

1 // Exercise 4.8 Solution: ex04_08.cpp


2 // Find the smallest of several integers.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int number; // number of values
9 int value; // current value
10 int smallest; // smallest value so far
11
12 cout << "Enter the number of integers to be processed ";
13 cout << "followed by the integers: " << endl;
14 cin >> number >> smallest;
15
16 // loop (number -1) times
17 for ( int i = 2; i <= number; i++ )
18 {
19 cin >> value; // read in next value
20
21 // if current value less than smallest, update smallest
22 if ( value < smallest )
23 smallest = value;
24 } // end for
25
26 // display smallest integer
27 cout << "\nThe smallest integer is: " << smallest << endl;
28 } // end main

Enter the number of integers to be processed followed by the integers:


6 10 3 15 21 26 14

The smallest integer is: 3

4.9 (Product of Odd Integers) Write a program that uses a for statement to calculate and print
the product of the odd integers from 1 to 15.
ANS:

1 // Exercise 4.9 Solution: ex04_09.cpp


2 // Calculate and print product of odd integers from 1 to 15.
3 #include <iostream>

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
76 Chapter 4 Control Statements, Part 2: Solutions

4 using namespace std;


5
6 int main()
7 {
8 int product = 1;
9
10 // calculate product
11 // increment counter i by 2 for odd numbers
12 for ( int i = 3; i <= 15; i += 2 )
13 product *= i;
14
15 // display resulting product
16 cout << "Product of the odd integers from 1 to 15 is: "
17 << product << endl;
18 } // end main

Product of the odd integers from 1 to 15 is: 2027025

4.10 (Factorials) The factorial function is used frequently in probability problems. Using the
definition of factorial in Exercise 3.34, write a program that uses a for statement to evaluate the
factorials of the integers from 1 to 5. Print the results in tabular format. What difficulty might pre-
vent you from calculating the factorial of 20?
ANS: Calculating the factorial of 20 might be difficult, because it might be such a large
number that it would not fit in an int or long variable.

1 // Exercise 4.10 Solution: ex04_10.cpp


2 // Factorial program.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int factorial = 1; // current factorial value
9
10 // display table headers
11 cout << "x\tx!\n";
12
13 // display factorial of numbers 1-5
14 for ( int i = 1; i <= 5; i++ )
15 {
16 factorial *= i; // i!
17
18 // display factorial value in table
19 cout << i << '\t' << factorial << '\n';
20 } // end for
21
22 cout << endl;
23 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 77

x x!
1 1
2 2
3 6
4 24
5 120

4.11 (Compound Interest) Modify the compound interest program of Section 4.4 to repeat its steps
for the interest rates 5%, 6%, 7%, 8%, 9% and 10%. Use a for statement to vary the interest rate.
ANS:

1 // Exercise 4.11 Solution: ex04_11.cpp


2 // Calculating compound interest with several interest rates.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 #include <cmath> // math functions
6 using namespace std;
7
8 int main()
9 {
10 double amount; // amount on deposit
11 double principal = 1000.0; // starting principal
12
13 // set floating-point number format
14 cout << fixed << setprecision( 2 );
15
16 // loop through interest rates 5% to 10%
17 for ( int rate = 5; rate <= 10; rate++ )
18 {
19 // display table headers
20 cout << "Interest Rate: " << rate << "%"
21 << "\nYear\tAmount on deposit\n";
22
23 // calculate amount on deposit for each of ten years
24 for ( int year = 1; year <= 10; year++ )
25 {
26 // calculate new amount for specified year
27 amount = principal * pow( 1 + ( rate / 100.0 ), year );
28
29 // output one table row
30 cout << year << '\t' << amount << '\n';
31 } // end for
32
33 cout << '\n';
34 } // end for
35
36 cout << endl;
37 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
78 Chapter 4 Control Statements, Part 2: Solutions

Interest Rate: 5%
Year Amount on deposit
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89

...

Interest Rate: 10%


Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74

4.12 (Drawing Patterns with Nested for Loops) Write a program that uses for statements to
print the following patterns separately, one below the other. Use for loops to generate the patterns.
All asterisks (*) should be printed by a single statement of the form cout << '*'; (this causes the
asterisks to print side by side). [Hint: The last two patterns require that each line begin with an ap-
propriate number of blanks. Extra credit: Combine your code from the four separate problems into
a single program that prints all four patterns side by side by making clever use of nested for loops.]
(a) (b) (c) (d)
* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********

ANS:

1 // Exercise 4.12 Solution: ex04_12.cpp


2 // Create triangles of asterisks using nested for loops.
3 #include <iostream>
4 using namespace std;
5

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 79

6 int main()
7 {
8 int row; // the row position
9 int column; // the column position
10 int space; // number of spaces to print
11
12 // first triangle
13 for ( row = 1; row <= 10; row++ )
14 {
15 for ( column = 1; column <= row; column++ )
16 cout << "*";
17
18 cout << endl;
19 } // end for
20
21 cout << endl;
22
23 // second triangle
24 for ( row = 10; row >= 1; row-- )
25 {
26 for ( column = 1; column <= row; column++ )
27 cout << "*";
28
29 cout << endl;
30 } // end for
31
32 cout << endl;
33
34 // third triangle
35 for ( row = 10; row >= 1; row-- )
36 {
37 for ( space = 10; space > row; space-- )
38 cout << " ";
39
40 for ( column = 1; column <= row; column++ )
41 cout << "*";
42
43 cout << endl;
44 } // end for
45
46 cout << endl;
47
48 // fourth triangle
49 for ( row = 10; row >= 1; row-- )
50 {
51 for ( space = 1; space < row; space++ )
52 cout << " ";
53
54 for ( column = 10; column >= row; column-- )
55 cout << "*";
56
57 cout << endl;
58 } // end for
59 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
80 Chapter 4 Control Statements, Part 2: Solutions

*
**
***
****
*****
******
*******
********
*********
**********

**********
*********
********
*******
******
*****
****
***
**
*

**********
*********
********
*******
******
*****
****
***
**
*

*
**
***
****
*****
******
*******
********
*********
**********

ANS: Extra-credit solution that prints the triangles side by side:

1 // Exercise 4.12 Extra Credit Solution: ex04_12.cpp


2 // Create triangles of asterisks side-by-side using nested for loops
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int row; // the row position
9 int column; // the column position
10 int space; // number of spaces to print
11
12 // print one row at a time, tabbing between triangles
13 for ( row = 1; row <= 10; row++ )
14 {

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 81

15 // first triangle
16 for ( column = 1; column <= row; column++ )
17 cout << "*";
18
19 for ( space = 1; space <= 10 - row; space++ )
20 cout << " ";
21
22 cout << "\t";
23
24 // second triangle
25 for ( column = 10; column >= row; column-- )
26 cout << "*";
27
28 for ( space = 1; space < row; space++ )
29 cout << " ";
30
31 cout << "\t";
32
33 // third triangle
34 for ( space = 1; space < row; space++ )
35 cout << " ";
36
37 for ( column = 10; column >= row; column-- )
38 cout << "*";
39
40 cout << "\t";
41
42 // fourth triangle
43 for ( space = 10; space > row; space-- )
44 cout << " ";
45
46 for ( column = 1; column <= row; column++ )
47 cout << "*";
48
49 cout << endl;
50 } // end for
51 } // end main

* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********

4.13 (Bar Chart) One interesting application of computers is drawing graphs and bar charts.
Write a program that reads five numbers (each between 1 and 30). Assume that the user enters only
valid values. For each number that is read, your program should print a line containing that number
of adjacent asterisks. For example, if your program reads the number 7, it should print *******.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
82 Chapter 4 Control Statements, Part 2: Solutions

ANS:

1 // Exercise 4.13 Solution: ex04_13.cpp


2 // Displaying bar charts using asterisks.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int number; // current number
9
10 cout << "Enter 5 numbers between 1 and 30: ";
11
12 // loop 5 times
13 for ( int i = 1; i <= 5; i++ )
14 {
15 cin >> number; // get a number from the user
16
17 // print asterisks corresponding to current input
18 for ( int j = 1; j <= number; j++ )
19 cout << '*';
20
21 cout << endl;
22 } // end for
23
24 cout << endl;
25 } // end main

Enter 5 numbers between 1 and 30: 16 12 8 27 9


****************
************
********
***************************
*********

4.14 (Calculating Total Sales) A mail order house sells five different products whose retail prices
are: product 1 — $2.98, product 2—$4.50, product 3—$9.98, product 4—$4.49 and product 5—
$6.87. Write a program that reads a series of pairs of numbers as follows:
a) product number
b) quantity sold
Your program should use a switch statement to determine the retail price for each product. Your
program should calculate and display the total retail value of all products sold. Use a sentinel-con-
trolled loop to determine when the program should stop looping and display the final results.
ANS:

1 // Exercise 4.14 Solution: ex04_14.cpp


2 // Calculate sales, based on an product number and quantity sold
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 using namespace std;
6

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 83

7 int main()
8 {
9 double product1 = 0; // amount sold of first product
10 double product2 = 0; // amount sold of second product
11 double product3 = 0; // amount sold of third product
12 double product4 = 0; // amount sold of fourth product
13 double product5 = 0; // amount sold of fifth product
14
15 int productId = 1; // current product id number
16 int quantity; // quantity of current product sold
17
18 // set floating-point number format
19 cout << fixed << setprecision( 2 );
20
21 // ask user for product number until flag value entered
22 while ( productId != -1 )
23 {
24 // determine the product chosen
25 cout << "Enter product number (1-5) (-1 to stop): ";
26 cin >> productId;
27
28 // verify product id
29 if ( productId >= 1 && productId <= 5 )
30 {
31 // determine the number sold of the item
32 cout << "Enter quantity sold: ";
33 cin >> quantity;
34
35 // increment the total for the item by the
36 // price times the quantity sold
37 switch ( productId )
38 {
39 case 1:
40 product1 += quantity * 2.98;
41 break;
42
43 case 2:
44 product2 += quantity * 4.50;
45 break;
46
47 case 3:
48 product3 += quantity * 9.98;
49 break;
50
51 case 4:
52 product4 += quantity * 4.49;
53 break;
54
55 case 5:
56 product5 += quantity * 6.87;
57 break;
58 } // end switch
59 } // end if

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
84 Chapter 4 Control Statements, Part 2: Solutions

60 else if ( productId != -1 )
61 cout <<
62 "Product number must be between 1 and 5 or -1 to stop" ;
63 } // end while
64
65 // print summary
66 cout << endl;
67 cout << "Product 1: $" << product1 << endl;
68 cout << "Product 2: $" << product2 << endl;
69 cout << "Product 3: $" << product3 << endl;
70 cout << "Product 4: $" << product4 << endl;
71 cout << "Product 5: $" << product5 << endl;
72 cout << "total: $"
73 << product1 + product2 + product3 + product4 + product5 << endl;
74 } // end main

Enter product number (1-5) (-1 to stop): 1


Enter quantity sold: 5
Enter product number (1-5) (-1 to stop): 5
Enter quantity sold: 10
Enter product number (1-5) (-1 to stop): -1

Product 1: $14.90
Product 2: $0.00
Product 3: $0.00
Product 4: $0.00
Product 5: $68.70
total: $83.60

4.15 (Grade Point Average) Modify the program of Fig. 4.9 to calculate the grade-point average.
A grade of A is worth 4 points, B is worth 3 points, and so on.
ANS:

1 // Exercise 4.15 Solution: ex04_15.cpp


2 // Create GradeBook object, input grades and display grade report.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 using namespace std;
6
7 int main()
8 {
9 int aCount = 0; // count of A grades
10 int bCount = 0; // count of B grades
11 int cCount = 0; // count of C grades
12 int dCount = 0; // count of D grades
13 int fCount = 0; // count of F grades
14 int grade; // grade entered by user
15
16 cout << "Enter the letter grades." << endl
17 << "Enter the EOF character to end input." << endl;
18

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 85

19 // loop until user types end-of-file key sequence


20 while ( ( grade = cin.get() ) != EOF )
21 {
22 // determine which grade was input
23 switch ( grade ) // switch statement nested in while
24 {
25 case 'A': // grade was uppercase A
26 case 'a': // or lowercase a
27 aCount++; // increment aCount
28 break; // exit switch
29
30 case 'B': // grade was uppercase B
31 case 'b': // or lowercase b
32 bCount++; // increment bCount
33 break; // exit switch
34
35 case 'C': // grade was uppercase C
36 case 'c': // or lowercase c
37 cCount++; // increment cCount
38 break; // exit switch
39
40 case 'D': // grade was uppercase D
41 case 'd': // or lowercase d
42 dCount++; // increment dCount
43 break; // exit switch
44
45 case 'F': // grade was uppercase F
46 case 'f': // or lowercase f
47 fCount++; // increment fCount
48 break; // exit switch
49
50 case '\n': // ignore newlines,
51 case '\t': // tabs,
52 case ' ': // and spaces in input
53 break; // exit switch
54
55 default: // catch all other characters
56 cout << "Incorrect letter grade entered."
57 << " Enter a new grade.\n";
58 break; // optional; will exit switch anyway
59 } // end switch
60 } // end while
61
62 // display summary of results
63 cout << "\n\nNumber of students who received each letter grade:"
64 << "\nA: " << aCount // display number of A grades
65 << "\nB: " << bCount // display number of B grades
66 << "\nC: " << cCount // display number of C grades
67 << "\nD: " << dCount // display number of D grades
68 << "\nF: " << fCount // display number of F grades
69 << endl;
70
71 // calculate total grades
72 int gradeCount = aCount + bCount + cCount + dCount + fCount;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
86 Chapter 4 Control Statements, Part 2: Solutions

73
74 // display class average
75 // if user entered at least one grade
76 if ( gradeCount != 0 )
77 {
78 // calculate total grades
79 int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;
80
81 // set floating-point number format
82 cout << fixed << setprecision( 1 );
83
84 // compute and display class GPA with 1 digit of precision
85 cout << "\nThe class average is: "
86 << static_cast< double > ( gradeTotal ) / gradeCount
87 << endl;
88 } // end if
89 } // end main

Welcome to the grade book for


CS101 C++ Programming!

Enter the letter grades.


Enter the EOF character to end input.
a
A
A
a
C
E
Incorrect letter grade entered. Enter a new grade.
F
^Z

Number of students who received each letter grade:


A: 4
B: 0
C: 1
D: 0
F: 1

The class average is: 3.0

4.16 (Compound Interest Calculation) Modify Fig. 4.6 so it uses only integers to calculate the
compound interest. [Hint: Treat all monetary amounts as numbers of pennies. Then “break” the re-
sult into its dollar and cents portions by using the division and modulus operations. Insert a period.]
ANS:

1 // Exercise 4.16 Solution: ex04_16.cpp


2 // Calculate compound interest using only integers.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 #include <cmath>
6 using namespace std;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 87

7
8 int main()
9 {
10 int amount; // amount on deposit, in pennies
11 int principal = 100000; // starting principal, in pennies ($1000)
12 int dollars; // dollar portion of amount
13 int cents; // cents portion of amount
14 double rate = .05; // interest rate
15
16 // display headers for table
17 cout << "Year" << setw( 24 ) << "Amount on deposit\n";
18
19 // loop 10 times
20 for ( int year = 1; year <= 10; year++ )
21 {
22 // determine new amount (in pennies)
23 amount = principal * pow( 1.0 + rate, year );
24
25 // determine cents portion of amount (last two digits)
26 cents = amount % 100;
27
28 // determine dollars portion of amount
29 // integer division truncates decimal places
30 dollars = amount / 100;
31
32 // display year, dollar portion followed by period
33 cout << setw( 4 ) << year << setw( 20 ) << dollars << '.';
34
35 // display cents portion
36 // if cents portion only 1 digit, insert 0
37 if ( cents < 10 )
38 cout << '0' << cents << endl;
39 else // else, display cents portion
40 cout << cents << endl;
41 } // end for
42 } // end main

Year Amount on deposit


1 1050.00
2 1102.50
3 1157.62
4 1215.50
5 1276.28
6 1340.09
7 1407.10
8 1477.45
9 1551.32
10 1628.89

4.17 (What Prints?) Assume i = 1, j = 2, k = 3 and m = 2. What does each statement print?
a) cout << ( i == 1 ) << endl;
ANS: 1.
b) cout << ( j == 3 ) << endl;
ANS: 0.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
88 Chapter 4 Control Statements, Part 2: Solutions

c) cout << ( i >= 1 && j < 4 ) << endl;


ANS: 1.
d) cout << ( m <= 99 && k < m ) << endl;
ANS: 0.
e) cout << ( j >= i || k == m ) << endl;
ANS: 1.
f) cout << ( k + m < j || 3 - j >= k ) << endl;
ANS: 0.
g) cout << ( !m ) << endl;
ANS: 0.
h) cout << ( !( j - m ) ) << endl;
ANS: 1.
i) cout << ( !( k > m ) ) << endl;
ANS: 0.
4.18 (Number Systems Table) Write a program that prints a table of the binary, octal and hexa-
decimal equivalents of the decimal numbers in the range 1–256. If you are not familiar with these
number systems, read Appendix D, Number Systems, first. [Hint: You can use the stream manipu-
lators dec, oct and hex to display integers in decimal, octal and hexadecimal formats, respectively.]
ANS:

1 // Exercise 4.18 Solution: ex04_18.cpp


2 // Display decimal, binary, octal and hexadecimal numbers.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int number; // loop counter for binary numbers
9 int factor; // current factor for binary numbers
10
11 // use tabs to display table headers
12 cout << "Decimal\t\tBinary\t\tOctal\tHexadecimal\n";
13
14 // loop from 1 to 256
15 for ( int loop = 1; loop <= 256; loop++ )
16 {
17 cout << dec << loop << "\t\t";
18
19 // output binary number
20 // initialize variables for calculating binary equivalent
21 number = loop;
22 factor = 256;
23
24 // output first digit
25 cout << ( number == 256 ? '1' : '0' );
26
27 // loop until factor is 1, i.e., last digit
28 do
29 {
30 // output current digit
31 cout <<
32 ( number < factor && number >= ( factor / 2 ) ? '1' : '0' );

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 89

33
34 // update factor and number variables
35 factor /= 2;
36 number %= factor;
37 } while ( factor > 1 );
38
39 // output octal number using oct stream manipulator
40 cout << '\t' << oct << loop;
41
42 // output hexadecimal number using hex stream manipulator
43 cout << '\t' << hex << loop << endl;
44 } // end for
45 } // end main

Decimal Binary Octal Hexadecimal


1 000000001 1 1
2 000000010 2 2
3 000000011 3 3
4 000000100 4 4
5 000000101 5 5

...

251 011111011 373 fb


252 011111100 374 fc
253 011111101 375 fd
254 011111110 376 fe
255 011111111 377 ff
256 100000000 400 100

4.19 (Calculating π) Calculate the value of π from the infinite series


4 4 4 4 4
π = 4 – --- + --- – --- + --- – ------ + …
3 5 7 9 11
Print a table that shows the approximate value of π after each of the first 1000 terms of this series.
ANS:

1 // Exercise 4.19 Solution: ex04_19.cpp


2 // Approximate value for pi.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 using namespace std;
6
7 int main()
8 {
9 long double pi = 0.0; // approximated value for pi
10 long double denom = 1.0; // denominator of current term
11 long accuracy = 1000; // number of terms
12
13 // set floating-point number format
14 cout << fixed << setprecision( 8 );
15
16 // display table headers

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
90 Chapter 4 Control Statements, Part 2: Solutions

17 cout << "Accuracy set at: " << accuracy << "\n\nterm\t\tpi\n";
18
19 // loop through each term
20 for ( long loop = 1; loop <= accuracy; loop++ )
21 {
22 if ( loop % 2 != 0 ) // if odd-numbered term, add current term
23 pi += 4.0 / denom;
24 else // if even-numbered term, subtract current term
25 pi -= 4.0 / denom;
26
27 // display number of terms and
28 // approximated value for pi with 8 digits of precision
29 cout << loop << "\t\t" << pi << '\n';
30
31 denom += 2.0; // update denominator
32 } // end for
33
34 cout << endl;
35 } // end main

Accuracy set at: 1000

term pi
1 4.00000000
2 2.66666667
3 3.46666667
4 2.89523810
5 3.33968254
6 2.97604618
7 3.28373848
8 3.01707182
9 3.25236593
10 3.04183962

...

990 3.14058255
991 3.14260174
992 3.14058459
993 3.14259970
994 3.14058662
995 3.14259768
996 3.14058864
997 3.14259566
998 3.14059065
999 3.14259365
1000 3.14059265

4.20 (Pythagorean Triples) A right triangle can have sides that are all integers. A set of three in-
teger values for the sides of a right triangle is called a Pythagorean triple. These three sides must sat-
isfy the relationship that the sum of the squares of two of the sides is equal to the square of the
hypotenuse. Find all Pythagorean triples for side1, side2 and hypotenuse all no larger than 500.
Use a triple-nested for loop that tries all possibilities. This is an example of brute force computing.
You’ll learn in more advanced computer science courses that there are many interesting problems
for which there is no known algorithmic approach other than sheer brute force.
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 91

ANS:

1 // Exercise 4.20 Solution: ex04_20.cpp


2 // Find Pythagorean triples using brute force computing.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int count = 0; // number of triples found
9 long int hypotenuseSquared; // hypotenuse squared
10 long int sidesSquared; // sum of squares of sides
11
12 cout << "Side 1\tSide 2\tSide3" << endl;
13
14 // side1 values range from 1 to 500
15 for ( long side1 = 1; side1 <= 500; side1++ )
16 {
17 // side2 values range from current side1 to 500
18 for ( long side2 = side1; side2 <= 500; side2++ )
19 {
20 // hypotenuse values range from current side2 to 500
21 for ( long hypotenuse = side2; hypotenuse <= 500; hypotenuse++ )
22 {
23 // calculate square of hypotenuse value
24 hypotenuseSquared = hypotenuse * hypotenuse;
25
26 // calculate sum of squares of sides
27 sidesSquared = side1 * side1 + side2 * side2;
28
29 // if (hypotenuse)^2 = (side1)^2 + (side2)^2,
30 // Pythagorean triple
31 if ( hypotenuseSquared == sidesSquared )
32 {
33 // display triple
34 cout << side1 << '\t' << side2 << '\t'
35 << hypotenuse << '\n';
36 count++; // update count
37 } // end if
38 } // end for
39 } // end for
40 } // end for
41
42 // display total number of triples found
43 cout << "A total of " << count << " triples were found." << endl;
44 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
92 Chapter 4 Control Statements, Part 2: Solutions

Side 1 Side 2 Side3


3 4 5
5 12 13
6 8 10
7 24 25
8 15 17

...

300 400 500


319 360 481
320 336 464
325 360 485
340 357 493
A total of 386 triples were found.

4.21 (Calculating Salaries) A company pays its employees as managers (who receive a fixed week-
ly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they work and
“time-and-a-half”—1.5 times their hourly wage—for overtime hours worked), commission workers
(who receive $250 plus 5.7 percent of their gross weekly sales), or pieceworkers (who receive a fixed
amount of money per item for each of the items they produce—each pieceworker in this company
works on only one type of item). Write a program to compute the weekly pay for each employee.
You do not know the number of employees in advance. Each type of employee has its own pay code:
Managers have code 1, hourly workers have code 2, commission workers have code 3 and piecework-
ers have code 4. Use a switch to compute each employee’s pay according to that employee’s paycode.
Within the switch, prompt the user (i.e., the payroll clerk) to enter the appropriate facts your pro-
gram needs to calculate each employee’s pay according to that employee’s paycode.
ANS:

1 // Exercise 4.21 Solution: ex04_21.cpp


2 // Calculate wages for each employee.
3 #include <iostream>
4 #include <iomanip> // parameterized stream manipulators
5 using namespace std;
6
7 int main()
8 {
9 int payCode; // current employee's pay code
10 int pieces; // current pieceworker's number of pieces
11 double salary; // current employee's salary
12 double hours; // current hourly employee's hours
13 double pay; // current employee's weekly pay
14
15 // prompt for first employee input
16 cout << "Enter paycode (-1 to end): ";
17 cin >> payCode;
18
19 // set floating-point number format
20 cout << fixed << setprecision( 2 );
21

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 93

22 // loop until sentinel value read from user


23 while ( payCode != -1 )
24 {
25 // switch to appropriate computation according to pay code
26 switch ( payCode )
27 {
28 case 1: // pay code 1 corresponds to manager
29 // prompt for weekly salary
30 cout << "Manager selected.\nEnter weekly salary: ";
31 cin >> salary;
32
33 // manager's pay is weekly salary
34 cout << "The manager's pay is $" << salary << '\n';
35 break; // exit switch
36
37 case 2: // pay code 2 corresponds to hourly worker
38 // prompt for hourly salary
39 cout << "Hourly worker selected.\n"
40 << "Enter the hourly salary: ";
41 cin >> salary;
42
43 // prompt for number of hours worked
44 cout << "Enter the total hours worked: ";
45 cin >> hours;
46
47 // pay fixed for up to 40 hours
48 // 1.5 for hours over 40
49 pay = ( hours > 40.0 ? ( hours - 40 ) * 1.5 * salary
50 + salary * 40.0 : salary * hours );
51
52 // display current employee's pay
53 cout << "Worker's pay is $" << pay << '\n';
54 break; // exit switch
55
56 case 3: // pay code 3 corresponds to commission worker
57 // prompt for gross weekly sales
58 cout << "Commission worker selected.\n"
59 << "Enter gross weekly sales: ";
60 cin >> salary;
61
62 // pay $250 plus 5.7% of gross weekly sales
63 pay = 250.0 + 0.057 * salary;
64
65 // display current employee's pay
66 cout << "Commission worker's pay is $" << pay << '\n';
67 break; // exit switch
68
69 case 4: // pay code 4 corresponds to pieceworker
70 // prompt for number of pieces
71 cout << "Pieceworker selected.\n"
72 << "Enter number of pieces: ";
73 cin >> pieces;
74

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
94 Chapter 4 Control Statements, Part 2: Solutions

75 // prompt for wage per piece


76 cout << "Enter wage per piece: ";
77 cin >> salary;
78
79 pay = pieces * salary; // compute pay
80
81 // display current employee's pay
82 cout << "Pieceworker's pay is $" << pay << '\n';
83 break; // exit switch
84
85 default: // default case
86 cout << "Invalid pay code.\n";
87 break;
88 } // end switch
89
90 // prompt for next employee input
91 cout << "\nEnter paycode (-1 to end): ";
92 cin >> payCode;
93 } // end while
94 } // end main

Enter paycode (-1 to end): 1


Manager selected.
Enter weekly salary: 1200
The manager's pay is $ 1200.00

Enter paycode (-1 to end): 2


Hourly worker selected.
Enter the hourly salary: 9.50
Enter the total hours worked: 20
Worker's pay is $ 190.00

Enter paycode (-1 to end): 3


Commission worker selected.
Enter gross weekly sales: 4000
Commission worker's pay is $ 478.00

Enter paycode (-1 to end): 4


Pieceworker selected.
Enter number of pieces: 50
Enter wage per piece: 3
Pieceworker's pay is $ 150.00

Enter paycode (-1 to end): -1

4.22 (De Morgan’s Laws) In this chapter, we discussed the logical operators &&, || and !. De
Morgan’s laws can sometimes make it more convenient for us to express a logical expression. These
laws state that the expression !( condition1 && condition2 ) is logically equivalent to the expression
( !condition1 || !condition2 ). Also, the expression !( condition1 || condition2 ) is logically equiv-
alent to the expression ( !condition1 && !condition2 ). Use De Morgan’s laws to write equivalent
expressions for each of the following, then write a program to show that the original expression and
the new expression in each case are equivalent:
a) !( x < 5 ) && !( y >= 7 )
b) !( a == b ) || !( g != 5 )
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 95

c) !( ( x <= 8 ) && ( y > 4 ) )


d) !( ( i > 4 ) || ( j <= 6 ) )
ANS:

1 // Exercise 4.22 Solution: ex04_22.cpp


2 // Prove DeMorgan’s law.
3 #include <iostream>
4 #include <iomanip>
5 using namespace std;
6
7 int main()
8 {
9 // Prove part (a)
10 // condition1: !(x < 5), condition2: !(y >= 7)
11 int x = 6; // make condition1 true first time through loop
12 int y; // variable for condition2
13
14 cout << boolalpha << "PART A" << endl << endl;
15
16 // loop twice for condition1 true, then false
17 do
18 {
19 x--; // make condition1 false second time through loop
20 y = 5; // make condition2 true first time through loop
21
22 // loop twice for condition2 true, then false
23 do
24 {
25 y++; // make condition2 false second time through loop
26
27 // display current assignments
28 cout << "!( x < 5 ): " << !( x < 5 ) << endl;
29 cout << "!( y >= 7 ): " << !( y >= 7 ) << endl;
30
31 // test for validity
32 if ( ( !( x < 5 ) && !( y >= 7 ) ) ==
33 ( !( ( x < 5 ) || ( y >= 7 ) ) ) )
34 cout << "!(x < 5) && !(y >= 7) is equivalent to"
35 << " !((x < 5) || (y >= 7))" << endl;
36 else
37 cout << "!(x < 5) && !(y >= 7) is not equivalent to"
38 << " !((x < 5) || (y >= 7))" << endl;
39
40 cout << endl;
41 } while ( !( y >= 7 ) ); // end do...while
42
43 } while ( !( x < 5 ) ); // end do...while
44
45 cout << endl << endl;
46
47 // Prove part (b)
48 // condition1: !(a == b), condition2: !(g != 5)
49 int a = 3; // make condition1 true first time through loop
50 int b = 5; // leave b at 5

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
96 Chapter 4 Control Statements, Part 2: Solutions

51 int g; // variable for condition2


52
53 cout << "PART B" << endl << endl;
54
55 // loop twice for condition1 true, then false
56 do
57 {
58 a++; // make condition1 false second time through loop
59 g = 4; // initially make condition2 true
60
61 // loop twice for condition2 true, then false
62 do
63 {
64 g++; // make condition2 false second time through loop
65
66 // display current assignments
67 cout << "!( a == b): " << !( a == b ) << endl;
68 cout << "!( g != 5): " << !( g != 5 ) << endl;
69
70 // test for validity
71 if ( ( !( a == b ) || !( g != 5 ) ) ==
72 ( !( ( a == b ) && ( g != 5 ) ) ) )
73 cout << "!(a == b) || !(g != 5) is equivalent to"
74 << " !((a == b) && (g != 5))" << endl;
75 else
76 cout << "!(a == b) || !(g != 5) is not equivalent to"
77 << " !((a == b) && (g != 5))" << endl;
78
79 cout << endl;
80 } while ( !( g != 5 ) ); // end do...while
81
82 } while ( !( a == b ) ); // end do...while
83
84 cout << endl << endl;
85
86 // Prove part (c)
87 // condition1: (x <= 8), condition2: (y > 4)
88 x = 7; // make condition1 true first time through loop
89
90 cout << "PART C" << endl << endl;
91
92 // loop twice for condition1 true, then false
93 do
94 {
95 x++; // make condition1 false second time through loop
96 y = 6; // initially make condition2 true
97
98 // loop twice for condition2 true, then false
99 do
100 {
101 y--; // make condition2 false second time through loop
102
103 // display current assignments
104 cout << "( x <= 8 ): " << ( x <= 8 ) << endl;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 97

105 cout << "( y > 4 ): " << ( y > 4 ) << endl;
106
107 // test for validity
108 if ( !( ( x <= 8 ) && ( y > 4 ) ) ==
109 ( !( x <= 8 ) || !( y > 4 ) ) )
110 cout << "!((x <= 8) && (y > 4)) is equivalent to"
111 << " !(x <= 8) || !(y > 4)" << endl;
112 else
113 cout << "!((x <= 8) && (y > 4)) is not equivalent to"
114 << " !(x <= 8) || !(y > 4)" << endl;
115
116 cout << endl;
117 } while ( ( y > 4 ) ); // end do...while
118
119 } while ( ( x <= 8 ) ); // end do...while
120
121 cout << endl << endl;
122
123 // Prove part (d)
124 // condition1: (i > 4), condition2: (j <= 6)
125 int i = 6; // make condition1 true first time through loop
126 int j; // variable for condition2
127
128 cout << "PART D" << endl << endl;
129
130 // loop twice for condition1 true, then false
131 do
132 {
133 i--; // make condition1 false second time through loop
134 j = 5; // initially make condition2 true
135
136 // loop twice for condition2 true, then false
137 do
138 {
139 j++; // make condition2 false second time through loop
140
141 // display current assignments
142 cout << "( i > 4 ): " << ( i > 4 ) << endl;
143 cout << "( j <= 6 ): " << ( j <= 6 ) << endl;
144
145 // test for validity
146 if ( !( ( i > 4 ) || ( j <= 6 ) ) ==
147 ( !( i > 4 ) && !( j <= 6 ) ) )
148 cout << "!((i > 4) || (j <= 6)) is equivalent to"
149 << " !(i > 4) && !(j <= 6)" << endl;
150 else
151 cout << "!((i > 4) || (j <= 6)) is not equivalent to"
152 << " !(i > 4) && !(j <= 6)" << endl;
153
154 cout << endl;
155 } while ( ( j <= 6 ) ); // end do...while
156
157 } while ( ( i > 4 ) ); // end do...while
158 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
98 Chapter 4 Control Statements, Part 2: Solutions

PART A

!( x < 5 ): true
!( y >= 7 ): true
!(x < 5) && !(y >= 7) is equivalent to !((x < 5) || (y >= 7))

!( x < 5 ): true
!( y >= 7 ): false
!(x < 5) && !(y >= 7) is equivalent to !((x < 5) || (y >= 7))

!( x < 5 ): false
!( y >= 7 ): true
!(x < 5) && !(y >= 7) is equivalent to !((x < 5) || (y >= 7))

!( x < 5 ): false
!( y >= 7 ): false
!(x < 5) && !(y >= 7) is equivalent to !((x < 5) || (y >= 7))

PART B

!( a == b): true
!( g != 5): true
!(a == b) || !(g != 5) is equivalent to !((a == b) && (g != 5))

!( a == b): true
!( g != 5): false
!(a == b) || !(g != 5) is equivalent to !((a == b) && (g != 5))

!( a == b): false
!( g != 5): true
!(a == b) || !(g != 5) is equivalent to !((a == b) && (g != 5))

!( a == b): false
!( g != 5): false
!(a == b) || !(g != 5) is equivalent to !((a == b) && (g != 5))

PART C

( x <= 8 ): true
( y > 4 ): true
!((x <= 8) && (y > 4)) is equivalent to !(x <= 8) || !(y > 4)

( x <= 8 ): true
( y > 4 ): false
!((x <= 8) && (y > 4)) is equivalent to !(x <= 8) || !(y > 4)

( x <= 8 ): false
( y > 4 ): true
!((x <= 8) && (y > 4)) is equivalent to !(x <= 8) || !(y > 4)

( x <= 8 ): false
( y > 4 ): false
!((x <= 8) && (y > 4)) is equivalent to !(x <= 8) || !(y > 4)

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 99

PART D

( i > 4 ): true
( j <= 6 ): true
!((i > 4) || (j <= 6)) is equivalent to !(i > 4) && !(j <= 6)

( i > 4 ): true
( j <= 6 ): false
!((i > 4) || (j <= 6)) is equivalent to !(i > 4) && !(j <= 6)

( i > 4 ): false
( j <= 6 ): true
!((i > 4) || (j <= 6)) is equivalent to !(i > 4) && !(j <= 6)

( i > 4 ): false
( j <= 6 ): false
!((i > 4) || (j <= 6)) is equivalent to !(i > 4) && !(j <= 6)

4.23 (Diamond of Asterisks) Write a program that prints the following diamond shape. You may
use output statements that print a single asterisk (*), a single blank or a single newline. Maximize
your use of repetition (with nested for statements) and minimize the number of output statements.

*
***
*****
*******
*********
*******
*****
***
*

ANS:

1 // Exercise 4.23 Solution: ex04_23.cpp


2 // Drawing a diamond shape with asterisks using nested control statements.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 // top half
9 for ( int row = 1; row <= 5; row++ )
10 {
11 // print preceding spaces
12 for ( int space = 1; space <= 5 - row; space++ )
13 cout << ' ';
14
15 // print asterisks
16 for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ )
17 cout << '*';
18

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
100 Chapter 4 Control Statements, Part 2: Solutions

19 cout << '\n';


20 } // end for
21
22 // bottom half
23 for ( int row = 4; row >= 1; row-- )
24 {
25 // print preceding spaces
26 for ( int space = 1; space <= 5 - row; space++ )
27 cout << ' ';
28
29 // print asterisks
30 for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ )
31 cout << '*';
32
33 cout << '\n';
34 } // end for
35
36 cout << endl;
37 } // end main

*
***
*****
*******
*********
*******
*****
***
*

4.24 (Diamond of Asterisks) Modify Exercise 4.23 to read an odd number in the range 1 to 19
to specify the number of rows in the diamond, then display a diamond of the appropriate size.
ANS:

1 // Exercise 4.24 Solution: ex04_24.cpp


2 // Drawing a diamond shape with the specified size.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int size; // number of rows in diamond
9
10 // loop until valid input
11 do
12 {
13 cout << "Enter an odd number for the diamond size (1-19): \n";
14 cin >> size;
15 } while ( ( size < 1 ) || ( size > 19 ) || ( ( size % 2 ) != 1 ) );
16

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 101

17 // top half
18 for ( int rows = 1; rows <= size - 2; rows += 2 )
19 {
20 // print preceding spaces
21 for ( int space = ( size - rows ) / 2; space > 0; space-- )
22 cout << ' ';
23
24 // print asterisks
25 for ( int asterisk = 1; asterisk <= rows; asterisk++ )
26 cout << '*';
27
28 cout << '\n';
29 } // end for
30
31 // bottom half
32 for ( rows = size; rows >= 0; rows -= 2 )
33 {
34 // print preceding spaces
35 for ( int space = ( size - rows ) / 2; space > 0; space-- )
36 cout << ' ';
37
38 // print asterisks
39 for ( int asterisk = 1; asterisk <= rows; asterisk++ )
40 cout << '*';
41
42 cout << '\n';
43 } // end for
44
45 cout << endl;
46 } // end main

Enter an odd number for the diamond size (1-19):


9
*
***
*****
*******
*********
*******
*****
***
*

Enter an odd number for the diamond size (1-19):


5
*
***
*****
***
*

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
102 Chapter 4 Control Statements, Part 2: Solutions

Enter an odd number for the diamond size (1-19):


7
*
***
*****
*******
*****
***
*

4.25 (Removing break and continue) A criticism of the break and continue statements is that
each is unstructured. These statements can always be replaced by structured statements. Describe in
general how you’d remove any break statement from a loop in a program and replace it with some
structured equivalent. [Hint: The break statement leaves a loop from within the body of the loop.
Another way to leave is by failing the loop-continuation test. Consider using in the loop-continua-
tion test a second test that indicates “early exit because of a ‘break’ condition.”] Use the technique
you developed here to remove the break statement from the program of Fig. 4.11.
ANS: A loop can be written without a break by placing in the loop-continuation test a sec-
ond test that indicates “early exit because of a ‘break’ condition.” In the body of the
loop, the break statement can be replaced with a statement setting a bool variable
(e.g., variable breakOut in the solution below) to true to indicate that a ‘break’
should occur. Any code appearing after the original break in the body of the loop can
be placed in a control statement that causes the program to skip this code when the
‘break’ condition is true. Doing so causes the ‘break’ to be the final statement execut-
ed in the body of the loop. After the ‘break’ condition has been met, the new “early
exit because of a ‘break’ condition” test in the loop-continuation test will be false,
causing the loop to terminate. Alternatively, the break can be replaced by a statement
that makes the original loop-continuation test immediately false, so that the loop ter-
minates. Again, any code following the original break must be placed in a control
statement that prevents it from executing when the ‘break’ condition is true.

1 // Exercise 4.25 Solution: ex04_25.cpp


2 // Terminating a loop without break.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int count; // control variable
9
10 // indicates whether 'break' condition has been reached
11 bool breakOut = false;
12
13 // indicate early exit because of 'break' condition;
14 // loop will end when breakOut has been set to true
15 for ( count = 1; ( count <= 10 ) && ( !breakOut ); count++ )
16 {
17 if ( count == 5 ) // 'break' condition
18 breakOut = true; // indicate that a break should occur

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 103

19 else
20 cout << count << " "; // skipped when 'break' condition is true
21 } // end for
22
23 cout << "\nBroke out of loop because loop-continuation test "
24 << "( !breakOut ) failed" << endl;
25 } // end main

1 2 3 4
Broke out of loop because loop-continuation test ( !breakOut ) failed

4.26 What does the following program segment do?

1 for ( int i = 1; i <= 5; i++ )


2 {
3 for ( int j = 1; j <= 3; j++ )
4 {
5 for ( int k = 1; k <= 4; k++ )
6 cout << '*';
7
8 cout << endl;
9 } // end inner for
10
11 cout << endl;
12 } // end outer for

ANS:

1 // Exercise 4.26 Solution: ex04_26.cpp


2 // Prints 5 groups of 3 lines, each containing 4 asterisks.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 for ( int i = 1; i <= 5; i++ )
9 {
10 for ( int j = 1; j <= 3; j++ )
11 {
12 for ( int k = 1; k <= 4; k++ )
13 cout << '*';
14
15 cout << endl;
16 } // end inner for
17
18 cout << endl;
19 } // end outer for
20 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
104 Chapter 4 Control Statements, Part 2: Solutions

****
****
****

****
****
****

****
****
****

****
****
****

****
****
****

4.27 (Removing the continue Statement) Describe in general how you’d remove any continue
statement from a loop in a program and replace it with some structured equivalent. Use the tech-
nique you developed here to remove the continue statement from the program of 4.12.
ANS: A loop can be rewritten without a continue statement by moving all the code that
appears in the body of the loop after the continue statement to an if statement that
tests for the opposite of the continue condition. Thus, the code that was originally
after the continue statement executes only when the if statement’s conditional ex-
pression is true (i.e., the “continue” condition is false). When the “continue” condi-
tion is true, the body of the if does not execute and the program “continues” to the
next iteration of the loop by not executing the remaining code in the loop’s body.

1 // Exercise 4.27 Solution: ex04_27.cpp


2 // Structured equivalent for continue statement.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 for ( int count = 1; count <= 10; count++ ) // loop 10 times
9 {
10 if ( count != 5 ) // if count == 5, skip to next iteration
11 cout << count << " ";
12 } // end for
13
14 cout << "\nUsed if condition to skip printing 5" << endl;
15 } // end main

1 2 3 4 6 7 8 9 10
Used if condition to skip printing 5

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 105

4.28 (“The Twelve Days of Christmas” Song) Write a program that uses repetition and switch
statements to print the song “The Twelve Days of Christmas.” One switch statement should be
used to print the day (i.e., “first,” “second,” etc.). A separate switch statement should be used to
print the remainder of each verse. Visit the website www.12days.com/library/carols/
12daysofxmas.htm for the complete lyrics to the song.
ANS:

1 // Exercise 4.28 Solution: ex04_28.cpp


2 // Display the 12 days of Christmas song.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 // loop 12 times
9 for ( int day = 1; day <= 12; day++ )
10 {
11 cout << "On the ";
12
13 // switch for current day
14 switch ( day )
15 {
16 case 1:
17 cout << "first";
18 break;
19 case 2:
20 cout << "second";
21 break;
22 case 3:
23 cout << "third";
24 break;
25 case 4:
26 cout << "fourth";
27 break;
28 case 5:
29 cout << "fifth";
30 break;
31 case 6:
32 cout << "sixth";
33 break;
34 case 7:
35 cout << "seventh";
36 break;
37 case 8:
38 cout << "eighth";
39 break;
40 case 9:
41 cout << "ninth";
42 break;
43 case 10:
44 cout << "tenth";
45 break;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
106 Chapter 4 Control Statements, Part 2: Solutions

46 case 11:
47 cout << "eleventh";
48 break;
49 case 12:
50 cout << "twelfth";
51 break;
52 } // end switch
53
54 cout << " day of Christmas,\nMy true love sent to me:\n";
55
56 // switch for gifts
57 switch ( day )
58 {
59 case 12:
60 cout << "\tTwelve drummers drumming,\n";
61 case 11:
62 cout << "\tEleven pipers piping,\n";
63 case 10:
64 cout << "\tTen lords a-leaping,\n";
65 case 9:
66 cout << "\tNine ladies dancing,\n";
67 case 8:
68 cout << "\tEight maids a-milking,\n";
69 case 7:
70 cout << "\tSeven swans a-swimming,\n";
71 case 6:
72 cout << "\tSix geese a-laying,\n";
73 case 5:
74 cout << "\tFive golden rings,\n";
75 case 4:
76 cout << "\tFour calling birds,\n";
77 case 3:
78 cout << "\tThree French hens,\n";
79 case 2:
80 cout << "\tTwo turtle doves, and\n";
81 case 1:
82 cout << "A partridge in a pear tree.\n\n\n";
83 } // end switch
84 } // end for
85
86 cout << endl;
87 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 107

On the first day of Christmas,


My true love sent to me:
A partridge in a pear tree.

On the second day of Christmas,


My true love sent to me:
Two turtle doves, and
A partridge in a pear tree.

...

On the twelfth day of Christmas,


My true love sent to me:
Twelve drummers drumming,
Eleven pipers piping,
Ten lords a-leaping,
Nine ladies dancing,
Eight maids a-milking,
Seven swans a-swimming,
Six geese a-laying,
Five golden rings,
Four calling birds,
Three French hens,
Two turtle doves, and
A partridge in a pear tree.

4.29 (Peter Minuit Problem) Legend has it that, in 1626, Peter Minuit purchased Manhattan
Island for $24.00 in barter. Did he make a good investment? To answer this question, modify the
compound interest program of Fig. 4.6 to begin with a principal of $24.00 and to calculate the
amount of interest on deposit if that money had been kept on deposit until this year (e.g., 384 years
through 2010). Place the for loop that performs the compound interest calculation in an outer for
loop that varies the interest rate from 5% to 10% to observe the wonders of compound interest.
ANS: [Note: Floating-point math is not exact, so the results may vary between computers.]

1 // Exercise 4.29 Solution: ex04_29.cpp


2 // Peter Minuit Problem:
3 // calculating compound interest with several interest rates.
4 #include <iostream>
5 #include <iomanip>
6 #include <cmath> // standard C++ math library
7 using namespace std;
8
9 int main()
10 {
11 double amount; // amount on deposit at end of each year
12 double principal = 24.0; // initial amount before interest
13 double rate; // interest rate
14
15 // set floating-point number format
16 cout << fixed << setprecision( 2 );
17

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
108 Chapter 4 Control Statements, Part 2: Solutions

18 // loop through interest rates 5% to 10%


19 for ( int rate = 5; rate <= 10; rate++ )
20 {
21 // display headers
22 cout << "\nInterest rate: " << rate << "%\n"
23 << "Year" << setw( 30 ) << "Amount on deposit" << endl;
24
25 // calculate amount on deposit for each of 384 years
26 for ( int year = 1; year <= 384; year++ )
27 {
28 // calculate new amount for specified year
29 amount = principal * pow( 1.0 + rate / 100.0, year );
30
31 // display the year and the amount
32 cout << setw( 4 ) << year << setw( 30 ) << amount << endl;
33 } // end inner for
34 } // end outer for
35
36 return 0; // indicate successful termination
37 } // end main

Interest rate: 5%
Year Amount on deposit
1 25.20
2 26.46
...
383 3131214255.24
384 3287774968.00

Interest rate: 6%
Year Amount on deposit
1 25.44
2 26.97
...
383 118129302081.03
384 125217060205.89

Interest rate: 7%
Year Amount on deposit
1 25.68
2 27.48
...
383 4307230317894.20
384 4608736440146.79

Interest rate: 8%
Year Amount on deposit
1 25.92
2 27.99
...
383 151883149141874.72
384 164033801073224.69

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Making a Difference 109

Interest rate: 9%
Year Amount on deposit
1 26.16
2 28.51
...
383 5182746332320663.00
384 5649193502229523.00

Interest rate: 10%


Year Amount on deposit
1 26.40
2 29.04
...
383 171241749947654144.00
384 188365924942419584.00

Making a Difference
4.30 (Global Warming Facts Quiz) The controversial issue of global warming has been widely
publicized by the film “An Inconvenient Truth,” featuring former Vice President Al Gore. Mr. Gore
and a U.N. network of scientists, the Intergovernmental Panel on Climate Change, shared the 2007
Nobel Peace Prize in recognition of “their efforts to build up and disseminate greater knowledge
about man-made climate change.” Research both sides of the global warming issue online (you
might want to search for phrases like “global warming skeptics”). Create a five-question multiple-
choice quiz on global warming, each question having four possible answers (numbered 1–4). Be ob-
jective and try to fairly represent both sides of the issue. Next, write an application that administers
the quiz, calculates the number of correct answers (zero through five) and returns a message to the
user. If the user correctly answers five questions, print “Excellent”; if four, print “Very good”; if
three or fewer, print “Time to brush up on your knowledge of global warming,” and include a list
of some of the websites where you found your facts.
ANS:

1 // Exercise 4.30 Solution: ex04_30.cpp


2 // Administers global warming quiz.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int answer; // answer user gave for current question
9 int score = 0; // number of correct answers
10
11 // first question
12 cout << "By how much have average temperatures risen since 1880?\n"
13 << "1: 0.4 degrees F\n"
14 << "2: 1.4 degrees F\n"
15 << "3: 2.4 degrees F\n"
16 << "4: 3.4 degrees F\n";
17
18 cout << "> "; // display prompt
19 cin >> answer; // read answer from user
20

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
110 Chapter 4 Control Statements, Part 2: Solutions

21 if ( answer == 2 )
22 {
23 ++score; // increment score if answer is correct
24 cout << "Correct!\n\n";
25 } // end if
26 else
27 cout << "Incorrect. The correct answer was 2\n\n";
28
29 // second question
30 cout << "Montana's Glacier National Park had 150 glaciers in 1910.\n"
31 << "How many does it have now?\n"
32 << "1: 0\n"
33 << "2: 7\n"
34 << "3: 17\n"
35 << "4: 27\n";
36
37 cout << "> "; // display prompt
38 cin >> answer; // read answer from user
39
40 if ( answer == 4 )
41 {
42 ++score; // increment score if answer is correct
43 cout << "Correct!\n\n";
44 } // end if
45 else
46 cout << "Incorrect. The correct answer was 4\n\n";
47
48 // third question
49 cout << "What is the most abundant greenhouse gas?\n"
50 << "1: water vapor\n"
51 << "2: carbon dioxide\n"
52 << "3: methane\n"
53 << "4: carbon monoxide\n";
54
55 cout << "> "; // display prompt
56 cin >> answer; // read answer from user
57
58 if ( answer == 1 )
59 {
60 ++score; // increment score if answer is correct
61 cout << "Correct!\n\n";
62 } // end if
63 else
64 cout << "Incorrect. The correct answer was 1\n\n";
65
66 // fourth question
67 cout
68 << "Which of these should you NOT do to help stop global warming?\n"
69 << "1: Use less hot water\n"
70 << "2: Reuse your shopping bag\n"
71 << "3: Plant a tree\n"
72 << "4: Take a bath instead of a shower\n";
73
74 cout << "> "; // display prompt

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Making a Difference 111

75 cin >> answer; // read answer from user


76
77 if ( answer == 4 )
78 {
79 ++score; // increment score if answer is correct
80 cout << "Correct!\n\n";
81 } // end if
82 else
83 cout << "Incorrect. The correct answer was 4\n\n";
84
85 // fifth question
86 cout
87 << "Which of these should you NOT do to help stop global warming?\n"
88 << "1: Buy more frozen foods\n"
89 << "2: Fly less\n"
90 << "3: Use a clothesline instead of a dryer\n"
91 << "4: Cover pots while cooking\n";
92
93 cout << "> "; // display prompt
94 cin >> answer; // read answer from user
95
96 if ( answer == 1 )
97 {
98 ++score; // increment score if answer is correct
99 cout << "Correct!\n\n";
100 } // end if
101 else
102 cout << "Incorrect. The correct answer was 1\n\n";
103
104 // display message based on number of correct answers
105 if ( score == 5 )
106 cout << "Excellent" << endl;
107 else if ( score == 4 )
108 cout << "Very good" << endl;
109 else
110 {
111 cout << "Time to brush up on your knowledge of global warming:\n"
112 << "http://news.nationalgeographic.com/news/2004/12/"
113 << "1206_041206_global_warming.html\n"
114 << "http://lwf.ncdc.noaa.gov/oa/climate/gases.html\n"
115 << "http://globalwarming-facts.info/50-tips.html\n";
116 } // end else
117 } // end main

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
112 Chapter 4 Control Statements, Part 2: Solutions

By how much have average temperatures risen since 1880?


1: 0.4 degrees F
2: 1.4 degrees F
3: 2.4 degrees F
4: 3.4 degrees F
> 2
Correct!

Montana's Glacier National Park had 150 glaciers in 1910.


How many does it have now?
1: 0
2: 7
3: 17
4: 27
> 3
Incorrect. The correct answer was 4

What is the most abundant greenhouse gas?


1: water vapor
2: carbon dioxide
3: methane
4: carbon monoxide
> 1
Correct!

Which of these should you NOT do to help stop global warming?


1: Use less hot water
2: Reuse your shopping bag
3: Plant a tree
4: Take a bath instead of a shower
> 4
Correct!

Which of these should you NOT do to help stop global warming?


1: Buy more frozen foods
2: Fly less
3: Use a clothesline instead of a dryer
4: Cover pots while cooking
> 1
Correct!

Very good

4.31 (Tax Plan Alternatives; The “FairTax”) There are many proposals to make taxation fairer.
Check out the FairTax initiative in the United States at
www.fairtax.org/site/PageServer?pagename=calculator

Research how the proposed FairTax works. One suggestion is to eliminate income taxes and most
other taxes in favor of a 23% consumption tax on all products and services that you buy. Some
FairTax opponents question the 23% figure and say that because of the way the tax is calculated, it
would be more accurate to say the rate is 30%—check this carefully. Write a program that prompts
the user to enter expenses in various expense categories they have (e.g., housing, food, clothing,
transportation, education, health care, vacations), then prints the estimated FairTax that person
would pay.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Solution Manual for C++ How to Program: Late Objects Version, 7/E 7th Edition Paul Deitel, H

Making a Difference 113

ANS:

1 // Exercise 4.31 Solution: ex04_31.cpp


2 // Calculates the tax the user would owe under the FairTax plan.
3 #include <iomanip>
4 #include <iostream>
5 using namespace std;
6
7 int main()
8 {
9 int amount; // amount the user pays for each expense
10 int total = 0;
11
12 // display the expense categories for the user
13 cout << "Welcome to the Fair Tax Calculator!\n"
14 << "Here are some common expense categories:\n"
15 << "1: Housing, 2: Food, 3: Clothing, 4: Transportation,\n"
16 << "5: Education, 6: Health care, 7: Vacations\n";
17
18 // prompt for and input the amount the user paid in each category
19 for ( int i = 1; i <= 7; ++i )
20 {
21 cout << "Total spending for category " << i << ": ";
22 cin >> amount;
23 total += amount;
24 } // end for
25
26 // calculate and display tax
27 double tax = total * 0.3;
28 cout << "Your total Fair Tax would be $" << setprecision( 2 )
29 << fixed << tax << endl;
30 } // end main

Welcome to the Fair Tax Calculator!


Here are some common expense categories:
1: Housing, 2: Food, 3: Clothing, 4: Transportation,
5: Education, 6: Health care, 7: Vacations
Total spending for category 1: 9600
Total spending for category 2: 3000
Total spending for category 3: 1000
Total spending for category 4: 2200
Total spending for category 5: 0
Total spending for category 6: 800
Total spending for category 7: 1300
Your total Fair Tax would be $5370.00

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Visit TestBankBell.com to get complete for all chapters

You might also like