Professional Documents
Culture Documents
Control
Statements:
Part 2
OBJECTIVES
In this chapter you will learn:
Benjamin Franklin
Henri Bergson
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
5.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. If no default action is needed, then there is no
need for a default case. Nevertheless, it is considered good software engineering 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 when the default case is the last case. Nor will the break statement
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.
5.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 variables 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 field width of 15 characters 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: Use the calculation x % 5. When the value of this is 0, print a newline character;
otherwise, print a tab character.]
ANS: x = 1;
while ( x <= 20 )
{
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
cout << x;
if ( x % 5 == 0 )
cout << endl;
else
cout << '\t';
x++;
}
or
for ( x = 1; x <= 20; x++ )
{
if ( x % 5 == 0 )
cout << x << endl;
else
cout << x << '\t';
}
5.3
Find the error(s) in each of the following code segments and explain how to correct it
(them).
a) x = 1;
while ( x <= 10 );
x++;
}
ANS: Error: The semicolon after the while header causes an infinite loop.
b)
Correction: Use an integer and perform the proper calculation in order 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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Correction: Add a break statement at the end of the statements for the first
Note that this is not an error if the programmer wants the statement of case
execute every time the case 1: statement executes.
d) The following code should print the values 1 to 10.
case.
2:
to
n = 1;
while ( n < 10 )
cout << n++ << endl;
ANS: Error: Improper relational operator used in the while repetition-continuation condi-
tion.
Correction: Use <= rather than <, or change 10 to 11.
Exercises
5.4
ANS: For should be for. The commas should be semicolons. The ++ should be a decrement
such as --.
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;
}
d) The following code should output the even integers from 2 to 100:
counter = 2;
do
{
cout << counter << endl;
counter += 2;
} While ( counter < 100 );
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
5.5
Write a program that uses a for statement to sum a sequence of integers. 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
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6
1
2
3
4
5
6
7
8
9
10
11
12
5.6
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
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
1
2
3
4
5
6
7
8
9
10
11
12
5.7
1
2
3
4
5
6
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main()
{
int x; // declare x
int y; // declare y
// prompt user for input
cout << "Enter two integers in the range 1-20: ";
cin >> x >> y; // read values for x and y
for ( int i = 1; i <= y; i++ ) // count from 1 to y
{
for ( int j = 1; j <= x; j++ ) // count from 1 to x
cout << '@'; // output @
cout << endl; // begin new line
} // end outer for
return 0; // indicate successful termination
} // end main
ANS:
Ouput:
Enter two integers in the range 1-20: 7 15
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
Explanation:
This program uses the rst 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.
5.8
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 and that the first number is not
one of the integers to compare.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
ANS:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
1
2
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10
3
4
5
6
7
8
9
10
11
12
5.9
Write a program that uses a for statement to calculate and print the product of the odd integers from 1 to 15.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
5.10 The factorial function is used frequently in probability problems. Using the definition of
factorial in Exercise 4.35, 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 prevent you from
calculating the factorial of 20?
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
11
ANS: Calculating the factorial of 20 might be difficult, because it might be such a large
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
x
1
2
3
4
5
5.11 Modify the compound interest program of Section 5.4 to repeat its steps for the interest
rates 5 percent, 6 percent, 7 percent, 8 percent, 9 percent and 10 percent. Use a for statement to
vary the interest rate.
ANS:
1
2
3
4
5
6
7
8
9
10
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
13
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
5.12 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 appropriate 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
2
3
4
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
1
2
3
4
5
6
7
8
9
10
11
12
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
15
16
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
ANS: Extra-credit solution that prints the triangles side by side:
1
2
3
4
5
6
7
8
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
17
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18
51
52
53
54
55
56
1
2
3
4
5
6
7
8
9
10
11
12
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
5.13 One interesting application of computers is the drawing of 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 *******.
ANS:
1
2
3
4
5
6
7
8
9
10
1
2
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
1
2
3
4
5
6
7
8
9
10
11
12
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
19
20
5.14 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-controlled loop to determine when the program should stop looping and display the nal results.
ANS:
1
2
3
4
5
6
7
8
9
10
11
//
//
//
//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
sold
sold
sold
sold
sold
of
of
of
of
of
first product
second product
third product
fourth product
fifth product
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
21
while ( productId != -1 )
{
// determine the product chosen
cout << "Enter product number (1-5) (-1 to stop): ";
cin >> productId;
// verify product id
if ( productId >= 1 && productId <= 5 )
{
// determine the number sold of the item
cout << "Enter quantity sold: ";
cin >> quantity;
// increment the total for the item by the
// price times the quantity sold
switch ( productId )
{
case 1:
product1 += quantity * 2.98;
break;
case 2:
product2 += quantity * 4.50;
break;
case 3:
product3 += quantity * 9.98;
break;
case 4:
product4 += quantity * 4.49;
break;
case 5:
product5 += quantity * 6.87;
break;
} // end switch
} // end if
else if ( productId != -1 )
cout <<
"Product number must be between 1 and 5 or -1 to stop" ;
} // end while
// print summary
cout << endl;
cout << "Product 1: $" << product1 << endl;
cout << "Product 2: $" << product2 << endl;
cout << "Product 3: $" << product3 << endl;
cout << "Product 4: $" << product4 << endl;
cout << "Product 5: $" << product5 << endl;
cout << "total: $"
<< product1 + product2 + product3 + product4 + product5 << endl;
} // end function calculateSales
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
22
1
2
3
4
5
6
7
8
9
10
11
12
Enter
Enter
Enter
Enter
Enter
product number
quantity sold:
product number
quantity sold:
product number
Product 1: $14.90
Product 2: $0.00
Product 3: $0.00
Product 4: $0.00
Product 5: $68.70
total: $83.60
5.15 Modify the GradeBook program of Fig. 5.9Fig. 5.11 so that it calculates the grade-point
average for the set of grades. A grade of A is worth 4 points, B is worth 3 points, etc.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
24
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
23
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
24
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
case 'C': //
case 'c': //
cCount++;
break; //
case 'D': //
case 'd': //
dCount++;
break; //
case 'F': //
case 'f': //
fCount++;
break; //
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
} // end while
} // end function inputGrades
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
25
by user
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
26
5.16 Modify the program in Fig. 5.6 so it uses only integers to calculate the compound interest.
[Hint: Treat all monetary amounts as integral numbers of pennies. Then break the result into its
dollar portion and cents portion by using the division and modulus operations. Insert a period.]
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
27
// loop 10 times
for ( int year = 1; year <= 10; year++ )
{
// determine new amount (in pennies)
amount = principal * pow( 1.0 + rate, year );
// determine cents portion of amount (last two digits)
cents = amount % 100;
// determine dollars portion of amount
// integer division truncates decimal places
dollars = amount / 100;
// display year, dollar portion followed by period
cout << setw( 4 ) << year << setw( 20 ) << dollars << '.';
// display cents portion
// if cents portion only 1 digit, insert 0
if ( cents < 10 )
cout << '0' << cents << endl;
else // else, display cents portion
cout << cents << endl;
} // end for
return 0; // indicate successful termination
} // end main
Year
1
2
3
4
5
6
7
8
9
10
Amount on deposit
1050.00
1102.50
1157.62
1215.50
1276.28
1340.09
1407.10
1477.45
1551.32
1628.89
5.17 Assume i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? Are
the parentheses necessary in each case?
a) cout << ( i == 1 ) << endl;
ANS: 1, no.
b) cout << ( j == 3 ) << endl;
ANS: 0, no.
c) cout << ( i >= 1 && j < 4 ) << endl;
ANS: 1, no.
d) cout << ( m <= 99 && k < m ) << endl;
ANS: 0, no.
e) cout << ( j >= i || k == m ) << endl;
ANS: 1, no.
f) cout << ( k + m < j || 3 - j >= k ) << endl;
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
28
g)
h)
ANS: 0, no.
ANS:
i)
5.18 Write a program that prints a table of the binary, octal and hexadecimal equivalents of the
decimal numbers in the range 1 through 256. If you are not familiar with these number systems,
read Appendix D, Number Systems, first.
ANS:
1
2
3
4
5
6
7
8
9
10
11
//
//
//
//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
1
2
3
4
5
6
7
8
9
10
11
12
29
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
30
Decimal
1
2
3
4
5
Binary
000000001
000000010
000000011
000000100
000000101
Octal
1
2
3
4
5
Hexadecimal
1
2
3
4
5
011111011
011111100
011111101
011111110
011111111
100000000
373
374
375
376
377
400
fb
fc
fd
fe
ff
100
...
251
252
253
254
255
256
5.19
Print a table that shows the approximate value of after each of the rst 1,000 terms of this series.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
30
31
32
33
34
35
36
37
38
39
40
31
pi
4.00000000
2.66666667
3.46666667
2.89523810
3.33968254
2.97604618
3.28373848
3.01707182
3.25236593
3.04183962
...
990
991
992
993
994
995
996
997
998
999
1000
3.14058255
3.14260174
3.14058459
3.14259970
3.14058662
3.14259768
3.14058864
3.14259566
3.14059065
3.14259365
3.14059265
5.20 (Pythagorean Triples) A right triangle can have sides that are all integers. A set of three integer
values for the sides of a right triangle is called a Pythagorean triple. These three sides must satisfy
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
will 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.
ANS:
1
2
3
4
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
32
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using std::endl;
int main()
{
int count = 0; // number of triples found
long int hypotenuseSquared; // hypotenuse squared
long int sidesSquared; // sum of squares of sides
cout << "Side 1\tSide 2\tSide3" << endl;
// side1 values range from 1 to 500
for ( long side1 = 1; side1 <= 500; side1++ )
{
// side2 values range from current side1 to 500
for ( long side2 = side1; side2 <= 500; side2++ )
{
// hypotenuse values range from current side2 to 500
for ( long hypotenuse = side2; hypotenuse <= 500; hypotenuse++ )
{
// calculate square of hypotenuse value
hypotenuseSquared = hypotenuse * hypotenuse;
// calculate sum of squares of sides
sidesSquared = side1 * side1 + side2 * side2;
// if (hypotenuse)^2 = (side1)^2 + (side2)^2,
// Pythagorean triple
if ( hypotenuseSquared == sidesSquared )
{
// display triple
cout << side1 << '\t' << side2 << '\t'
<< hypotenuse << '\n';
count++; // update count
} // end if
} // end for
} // end for
} // end for
// display total number of triples found
cout << "A total of " << count << " triples were found." << endl;
return 0; // indicate successful termination
} // end main
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
Side 1
3
5
6
7
8
Side 2
4
12
8
24
15
33
Side3
5
13
10
25
17
...
300
319
320
325
340
A total
400
500
360
481
336
464
360
485
357
493
of 386 triples were found.
5.21 A company pays its employees as managers (who receive a fixed weekly 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 wagefor 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 produceeach 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 pieceworkers have code 4. Use
a switch to compute each employees pay according to that employees paycode. Within the switch,
prompt the user (i.e., the payroll clerk) to enter the appropriate facts your program needs to calculate each employees pay according to that employees paycode.
ANS:
1
2
3
4
5
6
7
8
9
10
11
//
//
//
//
1
2
3
4
5
6
7
8
9
10
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
34
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
65
66
case 3: // pay code 3 corresponds to commission worker
67
// prompt for gross weekly sales
68
cout << "Commission worker selected.\n"
69
<< "Enter gross weekly sales: ";
70
cin >> salary;
71
72
// pay $250 plus 5.7% of gross weekly sales
73
pay = 250.0 + 0.057 * salary;
74
75
// display current employee's pay
76
cout << "Commission worker's pay is $" << pay << '\n';
77
break; // exit switch
78
79
case 4: // pay code 4 corresponds to pieceworker
80
// prompt for number of pieces
81
cout << "Pieceworker selected.\n"
82
<< "Enter number of pieces: ";
83
cin >> pieces;
84
85
// prompt for wage per piece
86
cout << "Enter wage per piece: ";
87
cin >> salary;
88
89
pay = pieces * salary; // compute pay
90
91
// display current employee's pay
92
cout << "Pieceworker's pay is $" << pay << '\n';
93
break; // exit switch
94
95
default: // default case
96
cout << "Invalid pay code.\n";
97
break;
98
} // end switch
99
100
// prompt for next employee input
101
cout << "\nEnter paycode (-1 to end): ";
102
cin >> payCode;
103
} // end while
104 } // end function calculateWage
1
2
3
4
5
6
7
8
9
10
11
12
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
35
36
5.22 (De Morgans Laws) In this chapter, we discussed the logical operators &&, || and !. De Morgans 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 equivalent to the expression ( !condition1 && !condition2 ). Use De Morgans 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 )
c) !( ( x <= 8 ) && ( y > 4 ) )
d) !( ( i > 4 ) || ( j <= 6 ) )
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
part
part
part
part
a
b
c
d
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
37
38
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
39
40
163
if ( !( ( i > 4 ) || ( j <= 6 ) ) ==
164
( !( i > 4 ) && !( j <= 6 ) ) )
165
cout << "!((i > 4) || (j <= 6)) is equivalent to"
166
<< " !(i > 4) && !(j <= 6)" << endl;
167
else
168
cout << "!((i > 4) || (j <= 6)) is not equivalent to"
169
<< " !(i > 4) && !(j <= 6)" << endl;
170
171
cout << endl;
172
} while ( ( j <= 6 ) ); // end do...while
173
174
} while ( ( i > 4 ) ); // end do...while
175 } // end function provePartD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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))
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
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)
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)
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
41
42
5.23 Write a program that prints the following diamond shape. You may use output statements
that print either a single asterisk (*) or a single blank. Maximize your use of repetition (with nested
for statements) and minimize the number of output statements.
*
***
*****
*******
*********
*******
*****
***
*
ANS:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
1
2
3
4
5
6
7
8
9
10
11
12
43
// bottom half
for ( int row = 4; row >= 1; row-- )
{
// print preceding spaces
for ( int space = 1; space <= 5 - row; space++ )
cout << ' ';
// print asterisks
for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ )
cout << '*';
cout << '\n';
} // end for
cout << endl;
} // end function drawDiamond
*
***
*****
*******
*********
*******
*****
***
*
5.24 Modify the program you wrote in Exercise 5.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
2
3
4
5
6
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
44
7
8
9
10
{
public:
void drawDiamond(); // draw diamond shape
}; // end class Diamond
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
49
50
51
52
1
2
3
4
5
6
7
8
9
10
11
12
} // end for
cout << endl;
} // end function drawDiamond
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
45
46
5.25 A criticism of the break and continue statements is that each is unstructured. Actually they
statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you would 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 loopcontinuation 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. 5.13.
ANS: A loop can be written without a break by placing in the loop-continuation test a second 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 executed 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 terminates. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
1 2 3 4
Broke out of loop because loop-continuation test ( !breakOut ) failed
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
5.26
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
47
48
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
5.27 Describe in general how you would remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the technique you developed here to remove the continue statement from the program of Fig. 5.14.
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 statements conditional expression is true (i.e., the continue condition is false). When the continue condition 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 loops body.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 2 3 4 6 7 8 9 10
Used if condition to skip printing 5
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
49
5.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 Web site www.12days.com/library/carols/
12daysofxmas.htm for the complete lyrics to the song.
ANS:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
50
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
89
90
91
92
93
1
2
3
4
5
6
7
8
9
10
11
12
51
} // end switch
} // end for
cout << endl;
} // end function printSong
5.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. 5.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., 379 years
through 2005). Place the for loop that performs the compound interest calculation in an outer for
loop that varies the interest rate from 5 percent to 10 percent to observe the wonders of compound
interest.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
Interest rate: 5%
Year
Amount on deposit
1
25.20
2
26.46
...
378
2453388301.80
379
2576057716.89
Interest rate: 6%
Year
Amount on deposit
1
25.44
2
26.97
...
378
88273086435.01
379
93569471621.11
Interest rate: 7%
Year
Amount on deposit
1
25.68
2
27.48
...
378
3070995688511.67
379
3285965386707.49
Interest rate: 8%
Year
Amount on deposit
1
25.92
2
27.99
...
378
103369119218531.97
379
111638648756014.53
Interest rate: 9%
Year
Amount on deposit
1
26.16
2
28.51
...
378
3368429508597858.50
379
3671588164371666.00
Interest rate: 10%
Year
Amount on deposit
1
26.40
2
29.04
...
378
106327653940462928.00
379
116960419334509232.00
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
53