Professional Documents
Culture Documents
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.
x++;
}
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 71
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;
}
do
{
cout << counter << endl;
counter += 2;
} While ( counter < 100 );
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 73
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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
74 Chapter 4 Control Statements, Part 2: Solutions
ANS:
Ouput:
© 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:
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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
76 Chapter 4 Control Statements, Part 2: Solutions
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.
© 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:
© 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
...
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:
© 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
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
© 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:
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:
© 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
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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 85
© 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
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:
© 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
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
© 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
...
© 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
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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
92 Chapter 4 Control Statements, Part 2: Solutions
...
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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises 93
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
94 Chapter 4 Control Statements, Part 2: Solutions
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
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
96 Chapter 4 Control Statements, Part 2: Solutions
© 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:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
100 Chapter 4 Control Statements, Part 2: Solutions
*
***
*****
*******
*********
*******
*****
***
*
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:
© 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
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
102 Chapter 4 Control Statements, Part 2: Solutions
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.
© 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
ANS:
© 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 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:
© 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
...
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.]
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
108 Chapter 4 Control Statements, Part 2: Solutions
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
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:
© 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
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
112 Chapter 4 Control Statements, Part 2: Solutions
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
ANS:
© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.