You are on page 1of 53

5

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.

Control
Statements:
Part 2
OBJECTIVES
In this chapter you will learn:

Benjamin Franklin

Intelligence is the faculty


of making articial objects,
especially tools to make tools.

Henri Bergson

Every advantage in the past


is judged in the light of the
nal issue.
Demosthenes

The essentials of counter-controlled repetition.


To use the for and dowhile repetition statements to
execute statements in a program repeatedly.
To understand multiple selection using the switch
selection statement.
To use the break and continue program control
statements to alter the ow 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.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 5 Control Statements: Part 2

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++;
}

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


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

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: Replace the semicolon by a {, or remove both the ; and the }.

for ( y = .1; y != 1.0; y += .1 )


cout << y << endl;

ANS: Error: Using a floating-point number to control a for repetition statement.

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.

Chapter 5 Control Statements: Part 2


cout << "The number is 2" << endl;
break;
default:
cout << "The number is not 1 or 2" << endl;
break;
}

ANS: Error: Missing break statement in the first case.

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

Find the error(s) 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 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;
}

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 <=.

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

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


ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 5.5 Solution: Sum.h


// Definition of class Sum that sums sequence of integers.
// Member functions are defined in Sum.cpp

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

// Exercise 5.5 Solution: Sum.cpp


// Member-function definitions for class Sum that sum
// sequence of integers.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Sum class definition


class Sum
{
public:
void sum(); // function to sum sequence of integers
}; // end class Sum

// include definition of class Sum from Sum.h


#include "Sum.h"
// function to sum sequence of integers
void Sum::sum()
{
int total = 0; // current total
int number; // number of values
int value; // current value
// display prompt
cout << "Enter the number of values to be summed "
<< "followed by the values: \n";
cin >> number; // input number of values
// loop number times
for ( int i = 1; i <= number; i++ )
{
cin >> value;
total += value;
} // end for
// display total
cout << "Sum of the " << number << " values is " << total << endl;
} // end function sum

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

6
1
2
3
4
5
6
7
8
9
10
11
12

Chapter 5 Control Statements: Part 2

// Exercise 5.5 Solution: ex05_05.cpp


// Create Sum object and invoke its sum function.
// include definition of class Sum from Sum.h
#include "Sum.h"
int main()
{
Sum application; // create Sum object
application.sum(); // call its sum function
return 0; // indicate program ended successfully
} // 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

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

// Exercise 5.6 Solution: Average.h


// Definition of class Average that calculates the average of integers.
// Member functions are defined in Average.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// Exercise 5.6 Solution: Average.cpp


// Member-function definitions for class Average that calculates
// the average of several integers.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Average class definition


class Average
{
public:
void calculateAverage(); // function to calculate average of integers
}; // end class Average

// include definition of class Average from Average.h


#include "Average.h"
// function to calculate the average of several integers
void Average::calculateAverage()
{
int value; // current value

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

int count = 0; // number of inputs


int total = 0; // sum of inputs
// prompt for input
cout << "Enter integers (9999 to end):" << endl;
cin >> value;
// loop until sentinel value read from user
while ( value != 9999 )
{
total += value; // update sum
count++; // update number of inputs
cin >> value; // read in next value
} // end while
// if user entered at least one value
if ( count != 0 )
cout << "\nThe average is: "
<< static_cast< double > ( total ) / count << endl;
else
cout << "\nNo values were entered." << endl;
} // end function calculateAverage

// Exercise 5.6 Solution: ex05_06.cpp


// Create Average object and invoke its calculateAverage function.
// include definition of class Average from Average.h
#include "Average.h"
int main()
{
Average application; // create Average object
application.calculateAverage(); // call its calculateAverage function
return 0; // indicate program ended successfully
} // end main

Enter integers (9999 to end):


10 8 11 7 9 9999
The average is: 9

5.7
1
2
3
4
5
6

What does the following program do?


// Exercise 5.7: ex05_07.cpp
// What does this program print?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

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

Chapter 5 Control Statements: Part 2

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

// Exercise 5.8 Solution: Small.h


// Definition of class Small that finds the smallest integer.
// Member functions are defined in Small.cpp

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

// Exercise 5.8 Solution: Small.cpp


// Member-function definitions for class Small that finds
// the smallest integer.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2

// Small class definition


class Small
{
public:
void findSmallest(); // function to find the smallest integer
}; // end class Small

// include definition of class Small from Small.h


#include "Small.h"
// function to find the smallest integer
void Small::findSmallest()
{
int number; // number of values
int value; // current value
int smallest; // smallest value so far
cout << "Enter the number of integers to be processed ";
cout << "followed by the integers: " << endl;
cin >> number >> smallest;
// loop (number -1) times
for ( int i = 2; i <= number; i++ )
{
cin >> value; // read in next value
// if current value less than smallest, update smallest
if ( value < smallest )
smallest = value;
} // end for
// display smallest integer
cout << "\nThe smallest integer is: " << smallest << endl;
} // end function findSmallest

// Exercise 5.8 Solution: ex05_08.cpp


// Create Small object and invoke its findSmallest function.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10
3
4
5
6
7
8
9
10
11
12

Chapter 5 Control Statements: Part 2

// include definition of class Small from Small.h


#include "Small.h"
int main()
{
Small application; // create Small object
application.findSmallest(); // call its findSmallest function
return 0; // indicate program ended successfully
} // 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

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

// Exercise 5.9 Solution: ex05_09.cpp


// Calculate and print product of odd integers from 1 to 15.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int product = 1;
// calculate product
// increment counter i by 2 for odd numbers
for ( int i = 3; i <= 15; i += 2 )
product *= i;
// display resulting product
cout << "Product of the odd integers from 1 to 15 is: "
<< product << endl;
return 0; // indicate successful termination
} // end main

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

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

number that it would not fit in an int or long variable.

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

// Exercise 5.10 Solution: ex05_10.cpp


// Factorial program.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int factorial = 1; // current factorial value
// display table headers
cout << "x\tx!\n";
// display factorial of numbers 1-5
for ( int i = 1; i <= 5; i++ )
{
factorial *= i; // i!
// display factorial value in table
cout << i << '\t' << factorial << '\n';
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main
x!
1
2
6
24
120

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

// Exercise 5.11 Solution: ex05_11.cpp


// Calculating compound interest with several interest rates.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed; // fixed decimal notation
#include <iomanip> // parameterized stream manipulators
using std::setprecision; // sets numeric output precision

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

Chapter 5 Control Statements: Part 2

#include <cmath> // math functions


using std::pow; // enables program to use function pow
int main()
{
double amount; // amount on deposit
double principal = 1000.0; // starting principal
// set floating-point number format
cout << fixed << setprecision( 2 );
// loop through interest rates 5% to 10%
for ( int rate = 5; rate <= 10; rate++ )
{
// display table headers
cout << "Interest Rate: " << rate << "%"
<< "\nYear\tAmount on deposit\n";
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 10; year++ )
{
// calculate new amount for specified year
amount = principal * pow( 1 + ( rate / 100.0 ), year );
// output one table row
cout << year << '\t' << amount << '\n';
} // end for
cout << '\n';
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main

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

// Exercise 5.12 Solution: Triangles.h


// Definition of class Triangles that draws triangles.
// Member functions are defined in Triangles.cpp

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

14

Chapter 5 Control Statements: Part 2

5
6
7
8
9
10

// Triangles class definition


class Triangles
{
public:
void drawTriangles(); // function to draw triangles
}; // end class Triangles

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

// Exercise 5.12 Solution: Triangles.cpp


// Member-function definitions for class Triangles that draws triangles.
#include <iostream>
using std::cout;
using std::endl;
// include definition of class Triangles from Triangles.h
#include "Triangles.h"
// function to draw triangles
void Triangles::drawTriangles()
{
int row; // the row position
int column; // the column position
int space; // number of spaces to print
// first triangle
for ( row = 1; row <= 10; row++ )
{
for ( column = 1; column <= row; column++ )
cout << "*";
cout << endl;
} // end for
cout << endl;
// second triangle
for ( row = 10; row >= 1; row-- )
{
for ( column = 1; column <= row; column++ )
cout << "*";
cout << endl;
} // end for
cout << endl;
// third triangle
for ( row = 10; row >= 1; row-- )
{
for ( space = 10; space > row; space-- )
cout << " ";
for ( column = 1; column <= row; column++ )
cout << "*";

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

cout << endl;


} // end for
cout << endl;
// fourth triangle
for ( row = 10; row >= 1; row-- )
{
for ( space = 1; space < row; space++ )
cout << " ";
for ( column = 10; column >= row; column-- )
cout << "*";
cout << endl;
} // end for
} // end function drawTriangles

// Exercise 5.12 Solution: ex05_12.cpp


// Create Triangles object and invoke its drawTriangles function.
// include definition of class Triangles from Triangles.h
#include "Triangles.h"
int main()
{
Triangles application; // create Triangles object
application.drawTriangles(); // call its drawTriangles function
return 0; // indicate program ended successfully
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

15

16

Chapter 5 Control Statements: Part 2

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

1
2
3
4
5
6
7
8

// Exercise 5.12 Extra Credit Solution: Triangles.h


// Definition of class Triangles that draws triangles.
// Member functions are defined in Triangles.cpp
// Triangles class definition
class Triangles
{
public:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

17

9
10

void drawTriangles(); // function to draw triangles


}; // end class Triangles

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

// Exercise 5.12 Extra Credit Solution: Triangles.cpp


// Member-function definitions for class Triangles that draws triangles.
#include <iostream>
using std::cout;
using std::endl;
// include definition of class Triangles from Triangles.h
#include "Triangles.h"
// function to draw triangles
void Triangles::drawTriangles()
{
int row; // the row position
int column; // the column position
int space; // number of spaces to print
// print one row at a time, tabbing between triangles
for ( row = 1; row <= 10; row++ )
{
// first triangle
for ( column = 1; column <= row; column++ )
cout << "*";
for ( space = 1; space <= 10 - row; space++ )
cout << " ";
cout << "\t";
// second triangle
for ( column = 10; column >= row; column-- )
cout << "*";
for ( space = 1; space < row; space++ )
cout << " ";
cout << "\t";
// third triangle
for ( space = 1; space < row; space++ )
cout << " ";
for ( column = 10; column >= row; column-- )
cout << "*";
cout << "\t";
// fourth triangle
for ( space = 10; space > row; space-- )
cout << " ";

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

Chapter 5 Control Statements: Part 2

for ( column = 1; column <= row; column++ )


cout << "*";
cout << endl;
} // end for
} // end function drawTriangles

// Exercise 5.12 Extra Credit Solution: ex05_12.cpp


// Create Triangles object and invoke its drawTriangles function.
// include definition of class Triangles from Triangles.h
#include "Triangles.h"
int main()
{
Triangles application; // create Triangles object
application.drawTriangles(); // call its drawTriangles function
return 0; // indicate program ended successfully
} // end main

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

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

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

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

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

// Exercise 5.13 Solution: Graphs.h


// Definition of class Graphs that draws bar charts.
// Member functions are defined in Graphs.cpp
// Graphs class definition
class Graphs
{
public:
void drawBarCharts(); // function to draw bar charts
}; // end class Graphs

// Exercise 5.13 Solution: Graphs.cpp


// Member-function definitions for class Graphs that draws bar charts.

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

// Exercise 5.13 Solution: ex05_13.cpp


// Create Graphs object and invoke its drawBarCharts function.

// include definition of class Graphs from Graphs.h


#include "Graphs.h"
// function to draw bar charts
void Graphs::drawBarCharts()
{
int number; // current number
cout << "Enter 5 numbers between 1 and 30: ";
// loop 5 times
for ( int i = 1; i <= 5; i++ )
{
cin >> number; // get a number from the user
// print asterisks corresponding to current input
for ( int j = 1; j <= number; j++ )
cout << '*';
cout << endl;
} // end for
cout << endl;
} // end function drawBarCharts

// include definition of class Graphs from Graphs.h


#include "Graphs.h"
int main()
{
Graphs application; // create Graphs object
application.drawBarCharts(); // call its drawBarCharts function
return 0; // indicate program ended successfully
} // end main

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


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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

19

20

Chapter 5 Control Statements: Part 2

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

// Exercise 5.14 Solution: Sales.cpp


// Member-function definitions for class Sales.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed; // fixed decimal notation

Exercise 5.14 Solution: Sales.h


Definition of class Sales that calculates sales, based on an
input of product number and quantity sold.
Member functions are defined in Sales.cpp

// Sales class definition


class Sales
{
public:
void calculateSales(); // function to calculate sales
}; // end class Sales

#include <iomanip> // parameterized stream manipulators


using std::setprecision; // sets numeric output precision
// include definition of class Sales from Sales.h
#include "Sales.h"
// function to calculate sales
void Sales::calculateSales()
{
double product1 = 0; // amount
double product2 = 0; // amount
double product3 = 0; // amount
double product4 = 0; // amount
double product5 = 0; // amount

sold
sold
sold
sold
sold

of
of
of
of
of

first product
second product
third product
fourth product
fifth product

int productId = 1; // current product id number


int quantity; // quantity of current product sold
// set floating-point number format
cout << fixed << setprecision( 2 );
// ask user for product number until flag value entered

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

Chapter 5 Control Statements: Part 2

// Exercise 5.14 Solution: ex05_14.cpp


// Create Sales object and invoke its calculateSales function.
// include definition of class Sales from Sales.h
#include "Sales.h"
int main()
{
Sales application; // create Sales object
application.calculateSales(); // call its calculateSales function
return 0; // indicate program ended successfully
} // end main

Enter
Enter
Enter
Enter
Enter

product number
quantity sold:
product number
quantity sold:
product number

(1-5) (-1 to stop): 1


5
(1-5) (-1 to stop): 5
10
(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

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

// Exercise 5.15 Solution: GradeBook.h


// Definition of class GradeBook that counts A, B, C, D and F grades.
// Member functions are defined in GradeBook.cpp
#include <string> // program uses C++ standard string class
using std::string;
// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // constructor initializes course name
void setCourseName( string ); // function to set the course name
string getCourseName(); // function to retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display a report based on the grades
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
24
25

int fCount; // count of F grades


}; // end class GradeBook

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

// Exercise 5.15 Solution: GradeBook.cpp


// Member-function definitions for class GradeBook that
// uses a switch statement to count A, B, C, D and F grades.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::fixed; // fixed decimal notation

23

#include <iomanip> // parameterized stream manipulators


using std::setprecision; // sets numeric output precision
// include definition of class GradeBook from GradeBook.h
#include "GradeBook.h"
// constructor initializes courseName with string supplied as argument;
// initializes counter data members to 0
GradeBook::GradeBook( string name )
{
setCourseName( name ); // validate and store courseName
aCount = 0; // initialize count of A grades to 0
bCount = 0; // initialize count of B grades to 0
cCount = 0; // initialize count of C grades to 0
dCount = 0; // initialize count of D grades to 0
fCount = 0; // initialize count of F grades to 0
} // end GradeBook constructor
// function to set the course name; limits name to 25 or fewer characters
void GradeBook::setCourseName( string name )
{
if ( name.length() <= 25 ) // if name has 25 or fewer characters
courseName = name; // store the course name in the object
else // if name is longer than 25 characters
{ // set courseName to first 25 characters of parameter name
courseName = name.substr( 0, 25 ); // select first 25 characters
cout << "Name \"" << name << "\" exceeds maximum length (25).\n"
<< "Limiting courseName to first 25 characters.\n" << endl;
} // end if...else
} // end function setCourseName
// function to retrieve the course name
string GradeBook::getCourseName()
{
return courseName;
} // end function getCourseName
// display a welcome message to the GradeBook user
void GradeBook::displayMessage()
{
// this statement calls getCourseName to get the

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

Chapter 5 Control Statements: Part 2

// name of the course this GradeBook represents


cout << "Welcome to the grade book for\n" << getCourseName() << "!\n"
<< endl;
} // end function displayMessage
// input arbitrary number of grades from user; update grade counter
void GradeBook::inputGrades()
{
int grade; // grade entered by user
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
// loop until user types end-of-file key sequence
while ( ( grade = cin.get() ) != EOF )
{
// determine which grade was input
switch ( grade ) // switch statement nested in while
{
case 'A': // grade was uppercase A
case 'a': // or lowercase a
aCount++; // increment aCount
break; // exit switch
case 'B': //
case 'b': //
bCount++;
break; //

grade was uppercase B


or lowercase b
// increment bCount
exit switch

case 'C': //
case 'c': //
cCount++;
break; //

grade was uppercase C


or lowercase c
// increment cCount
exit switch

case 'D': //
case 'd': //
dCount++;
break; //

grade was uppercase D


or lowercase d
// increment dCount
exit switch

case 'F': //
case 'f': //
fCount++;
break; //

grade was uppercase F


or lowercase f
// increment fCount
exit switch

case '\n': // ignore newlines,


case '\t': // tabs,
case ' ': // and spaces in input
break; // exit switch
default: // catch all other characters
cout << "Incorrect letter grade entered."
<< " Enter a new grade.\n";
break; // optional; will exit switch anyway
} // end switch

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

// Exercise 5.15 Solution: ex05_15.cpp


// Create GradeBook object, input grades and display grade report.

// display a report based on the grades entered


void GradeBook::displayGradeReport()
{
// display summary of results
cout << "\n\nNumber of students who received
<< "\nA: " << aCount // display number of
<< "\nB: " << bCount // display number of
<< "\nC: " << cCount // display number of
<< "\nD: " << dCount // display number of
<< "\nF: " << fCount // display number of
<< endl;

25

by user

each letter grade:"


A grades
B grades
C grades
D grades
F grades

// calculate total grades


int gradeCount = aCount + bCount + cCount + dCount + fCount;
// display class average
// if user entered at least one grade
if ( gradeCount != 0 )
{
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;
// set floating-point number format
cout << fixed << setprecision( 1 );
// compute and display class GPA with 1 digit of precision
cout << "\nThe class average is: "
<< static_cast< double > ( gradeTotal ) / gradeCount
<< endl;
} // end if
} // end function displayGradeReport

// include definition of class GradeBook from GradeBook.h


#include "GradeBook.h"
int main()
{
// create GradeBook object myGradeBook and
// pass course name to constructor
GradeBook myGradeBook( "CS101 C++ Programming" );
myGradeBook.displayMessage(); // display welcome message
myGradeBook.inputGrades(); // read grades from user
myGradeBook.displayGradeReport(); // display report based on grades
return 0; // indicate successful termination
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

26

Chapter 5 Control Statements: Part 2

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

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

// Exercise 5.16 Solution: ex05_16.cpp


// Calculate compound interest using only integers.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip> // parameterized stream manipulators
using std::setw; // sets field width
#include <cmath>
using std::pow; // exponentiation function
int main()
{
int amount; // amount on deposit, in pennies
int principal = 100000; // starting principal, in pennies ($1000)
int dollars; // dollar portion of amount
int cents; // cents portion of amount
double rate = .05; // interest rate
// display headers for table
cout << "Year" << setw( 24 ) << "Amount on deposit\n";

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

Chapter 5 Control Statements: Part 2


ANS: 0, no.

g)

cout << ( !m ) << endl;

h)

cout << ( !( j - m ) ) << endl;

ANS: 0, no.
ANS:

i)

1, yes. The inner pair of parentheses are required.

cout << ( !( k > m ) ) << endl;

ANS: 0, yes. The inner pair of parentheses are required.

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

// Exercise 5.18 Solution: NumberSystem.cpp


// Member-function definitions for class NumberSystem that
// displays numbers in decimal, binary, octal and hexadecimal formats.
#include <iostream>
using std::cout;
using std::dec; // causes integers to be output in decimal
using std::endl;
using std::hex; // causes integers to be output in hexadecimal
using std::oct; // causes integers to be output in octal

Exercise 5.18 Solution: NumberSystem.h


Definition of class NumberSystem that displays decimal, binary
octal and hexadecimal numbers.
Member functions are defined in NumberSystem.cpp

// NumberSystem class definition


class NumberSystem
{
public:
void displayNumbers(); // display numbers in all formats
}; // end class NumberSystem

// include definition of class NumberSystem from NumberSystem.h


#include "NumberSystem.h"
// function to display numbers in various formats
void NumberSystem::displayNumbers()
{
int number; // loop counter for binary numbers
int factor; // current factor for binary numbers
// use tabs to display table headers
cout << "Decimal\t\tBinary\t\tOctal\tHexadecimal\n";
// loop from 1 to 256
for ( int loop = 1; loop <= 256; loop++ )
{
cout << dec << loop << "\t\t";

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

// output binary number


// initialize variables for calculating binary equivalent
number = loop;
factor = 256;
// output first digit
cout << ( number == 256 ? '1' : '0' );
// loop until factor is 1, i.e., last digit
do
{
// output current digit
cout <<
( number < factor && number >= ( factor / 2 ) ? '1' : '0' );
// update factor and number variables
factor /= 2;
number %= factor;
} while ( factor > 1 );
// output octal number using oct stream manipulator
cout << '\t' << oct << loop;
// output hexadecimal number using hex stream manipulator
cout << '\t' << hex << loop << endl;
} // end for
} // end function displayNumbers

// Exercise 5.18 Solution: ex05_18.cpp


// Create NumberSystem object, display numbers in various formats.
// include definition of class NumberSystem from NumberSystem.h
#include "NumberSystem.h"
int main()
{
NumberSystem application; // create NumberSystem object
application.displayNumbers(); // display numbers in various formats
return 0; // indicate successful termination
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

30

Chapter 5 Control Statements: Part 2

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

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 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

// Exercise 5.19 Solution: ex05_19.cpp


// Approximate value for pi.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed; // fixed decimal notation
#include <iomanip> // parameterized stream manipulators
using std::setprecision; // sets numeric output precision
int main()
{
long double pi = 0.0; // approximated value for pi
long double denom = 1.0; // denominator of current term
long accuracy = 1000; // number of terms
// set floating-point number format
cout << fixed << setprecision( 8 );
// display table headers
cout << "Accuracy set at: " << accuracy << "\n\nterm\t\tpi\n";
// loop through each term
for ( long loop = 1; loop <= accuracy; loop++ )
{
if ( loop % 2 != 0 ) // if odd-numbered term, add current term
pi += 4.0 / denom;
else // if even-numbered term, subtract current term
pi -= 4.0 / denom;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
30
31
32
33
34
35
36
37
38
39
40

31

// display number of terms and


// approximated value for pi with 8 digits of precision
cout << loop << "\t\t" << pi << '\n';
denom += 2.0; // update denominator
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main

Accuracy set at: 1000


term
1
2
3
4
5
6
7
8
9
10

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

// Exercise 5.20 Solution: ex05_20.cpp


// Find Pythagorean triples using brute force computing.
#include <iostream>
using std::cout;

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

Chapter 5 Control Statements: Part 2

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

// Exercise 5.21 Solution: Employees.cpp


// Member-function definitions for class Employees that
// calculates wage for each employee.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed; // fixed decimal notation

Exercise 5.21 Solution: Employees.h


Definition of class Employees that calculates wage
for each employee.
Member functions are defined in Employees.cpp

// Employees class definition


class Employees
{
public:
void calculateWage(); // calculate wage for employees
}; // end class Employees

#include <iomanip> // parameterized stream manipulators

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

Chapter 5 Control Statements: Part 2

using std::setprecision; // sets numeric output precision


// include definition of class Employees from Employees.h
#include "Employees.h"
// function to calculate wage
void Employees::calculateWage()
{
int payCode; // current employee's pay code
int pieces; // current pieceworker's number of pieces
double salary; // current employee's salary
double hours; // current hourly employee's hours
double pay; // current employee's weekly pay
// prompt for first employee input
cout << "Enter paycode (-1 to end): ";
cin >> payCode;
// set floating-point number format
cout << fixed << setprecision( 2 );
// loop until sentinel value read from user
while ( payCode != -1 )
{
// switch to appropriate computation according to pay code
switch ( payCode )
{
case 1: // pay code 1 corresponds to manager
// prompt for weekly salary
cout << "Manager selected.\nEnter weekly salary: ";
cin >> salary;
// manager's pay is weekly salary
cout << "The manager's pay is $" << salary << '\n';
break; // exit switch
case 2: // pay code 2 corresponds to hourly worker
// prompt for hourly salary
cout << "Hourly worker selected.\n"
<< "Enter the hourly salary: ";
cin >> salary;
// prompt for number of hours worked
cout << "Enter the total hours worked: ";
cin >> hours;
// pay fixed for up to 40 hours
// 1.5 for hours over 40
pay = ( hours > 40.0 ? ( hours - 40 ) * 1.5 * salary
+ salary * 40.0 : salary * hours );
// display current employee's pay
cout << "Worker's pay is $" << pay << '\n';
break; // exit switch

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

// Exercise 5.21 Solution: ex05_21.cpp


// Create Employees object, calculate wage for each employee.
// include definition of class Employees from Employees.h
#include "Employees.h"
int main()
{
Employees application; // create Employees object
application.calculateWage(); // calculate wage for each employee
return 0; // indicate successful termination
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

35

36

Chapter 5 Control Statements: Part 2

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

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

// Exercise 5.22 Solution: DeMorgan.h


// Definition of class DeMorgan that proves De Morgan's law.
// Member functions are defined in DeMorgan.cpp
// DeMorgan class definition
class DeMorgan
{
public:
void provePartA(); // prove
void provePartB(); // prove
void provePartC(); // prove
void provePartD(); // prove
}; // end class DeMorgan

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

// Exercise 5.22 Solution: DeMorgan.cpp


// Member-function definitions for class DeMorgan that
// proves De Morgan's law.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::boolalpha;
// include definition of class DeMorgan from DeMorgan.h
#include "DeMorgan.h"
// function to prove part a
void DeMorgan::provePartA()
{
// condition1: !(x < 5), condition2: !(y >= 7)
int x = 6; // make condition1 true first time through loop
int y; // variable for condition2
cout << boolalpha << "PART A" << endl << endl;
// loop twice for condition1 true, then false
do
{
x--; // make condition1 false second time through loop
y = 5; // make condition2 true first time through loop
// loop twice for condition2 true, then false
do
{
y++; // make condition2 false second time through loop
// display current assignments
cout << "!( x < 5 ): " << !( x < 5 ) << endl;
cout << "!( y >= 7 ): " << !( y >= 7 ) << endl;
// test for validity
if ( ( !( x < 5 ) && !( y >= 7 ) ) ==
( !( ( x < 5 ) || ( y >= 7 ) ) ) )
cout << "!(x < 5) && !(y >= 7) is equivalent to"
<< " !((x < 5) || (y >= 7))" << endl;
else
cout << "!(x < 5) && !(y >= 7) is not equivalent to"
<< " !((x < 5) || (y >= 7))" << endl;
cout << endl;
} while ( !( y >= 7 ) ); // end do...while
} while ( !( x < 5 ) ); // end do...while
cout << endl << endl;
} // end function provePartA

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

Chapter 5 Control Statements: Part 2

// function to prove part b


void DeMorgan::provePartB()
{
// condition1: !(a == b), condition2: !(g != 5)
int a = 3; // make condition1 true first time through loop
int b = 5; // leave b at 5
int g; // variable for condition2
cout << "PART B" << endl << endl;
// loop twice for condition1 true, then false
do
{
a++; // make condition1 false second time through loop
g = 4; // initially make condition2 true
// loop twice for condition2 true, then false
do
{
g++; // make condition2 false second time through loop
// display current assignments
cout << "!( a == b): " << !( a == b ) << endl;
cout << "!( g != 5): " << !( g != 5 ) << endl;
// test for validity
if ( ( !( a == b ) || !( g != 5 ) ) ==
( !( ( a == b ) && ( g != 5 ) ) ) )
cout << "!(a == b) || !(g != 5) is equivalent to"
<< " !((a == b) && (g != 5))" << endl;
else
cout << "!(a == b) || !(g != 5) is not equivalent to"
<< " !((a == b) && (g != 5))" << endl;
cout << endl;
} while ( !( g != 5 ) ); // end do...while
} while ( !( a == b ) ); // end do...while
cout << endl << endl;
} // end function provePartB
// function to prove part c
void DeMorgan::provePartC()
{
// condition1: (x <= 8), condition2: (y > 4)
int x = 7; // make condition1 true first time through loop
int y; // variable for condition2
cout << "PART C" << endl << endl;
// loop twice for condition1 true, then false
do
{

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

x++; // make condition1 false second time through loop


y = 6; // initially make condition2 true
// loop twice for condition2 true, then false
do
{
y--; // make condition2 false second time through loop
// display current assignments
cout << "( x <= 8 ): " << ( x <= 8 ) << endl;
cout << "( y > 4 ): " << ( y > 4 ) << endl;
// test for validity
if ( !( ( x <= 8 ) && ( y > 4 ) ) ==
( !( x <= 8 ) || !( y > 4 ) ) )
cout << "!((x <= 8) && (y > 4)) is equivalent to"
<< " !(x <= 8) || !(y > 4)" << endl;
else
cout << "!((x <= 8) && (y > 4)) is not equivalent to"
<< " !(x <= 8) || !(y > 4)" << endl;
cout << endl;
} while ( ( y > 4 ) ); // end do...while
} while ( ( x <= 8 ) ); // end do...while
cout << endl << endl;
} // end function provePartC
// function to prove part d
void DeMorgan::provePartD()
{
// condition1: (i > 4), condition2: (j <= 6)
int i = 6; // make condition1 true first time through loop
int j; // variable for condition2
cout << "PART D" << endl << endl;
// loop twice for condition1 true, then false
do
{
i--; // make condition1 false second time through loop
j = 5; // initially make condition2 true
// loop twice for condition2 true, then false
do
{
j++; // make condition2 false second time through loop
// display current assignments
cout << "( i > 4 ): " << ( i > 4 ) << endl;
cout << "( j <= 6 ): " << ( j <= 6 ) << endl;
// test for validity

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

39

40

Chapter 5 Control Statements: Part 2

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

// Exercise 5.22 Solution: ex05_22.cpp


// Create DeMorgan object, prove that the two expressions in each case
// produce the same value.
// include definition of class DeMorgan from DeMorgan.h
#include "DeMorgan.h"
int main()
{
DeMorgan application; // create DeMorgan object
application.provePartA(); // prove part a
application.provePartB(); // prove part b
application.provePartC(); // prove part c
application.provePartD(); // prove part d
return 0; // indicate successful termination
} // end main

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

Chapter 5 Control Statements: Part 2

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

// Exercise 5.23 Solution: Diamond.h


// Definition of class Diamond that draws diamond shape.
// Member functions are defined in Diamond.cpp

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

// Exercise 5.23 Solution: Diamond.cpp


// Member-function definitions for class Diamond that draws diamond shape.
#include <iostream>
using std::cout;
using std::endl;

// Diamond class definition


class Diamond
{
public:
void drawDiamond(); // draw diamond shape
}; // end class Diamond

// include definition of class Diamond from Diamond.h


#include "Diamond.h"
// function to draw diamond shape
void Diamond::drawDiamond()
{
// top half
for ( int row = 1; row <= 5; 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

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

// Exercise 5.23 Solution: ex05_23.cpp


// Create Diamond object, draw diamond shape.
// include definition of class Diamond from Diamond.h
#include "Diamond.h"
int main()
{
Diamond application; // create Diamond object
application.drawDiamond(); // draw diamond shape
return 0; // indicate successful termination
} // end main

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

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

// Exercise 5.24 Solution: Diamond.h


// Definition of class Diamond that draws diamond shape.
// Member functions are defined in Diamond.cpp
// Diamond class definition
class Diamond

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

44

Chapter 5 Control Statements: Part 2

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

// Exercise 5.24 Solution: Diamond.cpp


// Member-function definitions for class Diamond that draws diamond shape.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
// include definition of class Diamond from Diamond.h
#include "Diamond.h"
// function to draw diamond shape
void Diamond::drawDiamond()
{
int size; // number of rows in diamond
// loop until valid input
do
{
cout << "Enter an odd number for the diamond size (1-19): \n";
cin >> size;
} while ( ( size < 1 ) || ( size > 19 ) || ( ( size % 2 ) != 1 ) );
// top half
for ( int rows = 1; rows <= size - 2; rows += 2 )
{
// print preceding spaces
for ( int space = ( size - rows ) / 2; space > 0; space-- )
cout << ' ';
// print asterisks
for ( int asterisk = 1; asterisk <= rows; asterisk++ )
cout << '*';
cout << '\n';
} // end for
// bottom half
for ( rows = size; rows >= 0; rows -= 2 )
{
// print preceding spaces
for ( int space = ( size - rows ) / 2; space > 0; space-- )
cout << ' ';
// print asterisks
for ( int asterisk = 1; asterisk <= rows; asterisk++ )
cout << '*';
cout << '\n';

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

// Exercise 5.24 Solution: ex05_24.cpp


// Create Diamond object, draw diamond shape.
// include definition of class Diamond from Diamond.h
#include "Diamond.h"
int main()
{
Diamond application; // create Diamond object
application.drawDiamond(); // draw diamond shape
return 0; // indicate successful termination
} // end main

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


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

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


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

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


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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

45

46

Chapter 5 Control Statements: Part 2

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

// Exercise 5.25 Solution: ex05_25.cpp


// Terminating a loop without break.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int count; // control variable
// indicates whether 'break' condition has been reached
bool breakOut = false;
// indicate early exit because of 'break' condition;
// loop will end when breakOut has been set to true
for ( count = 1; ( count <= 10 ) && ( !breakOut ); count++ )
{
if ( count == 5 ) // 'break' condition
breakOut = true; // indicate that a break should occur
else
cout << count << " "; // skipped when 'break' condition is true
} // end for
cout << "\nBroke out of loop because loop-continuation test "
<< "( !breakOut ) failed" << endl;
return 0; // indicate successful termination
} // end main

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

What does the following program segment do?

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


{
for ( int j = 1; j <= 3; j++ )
{
for ( int k = 1; k <= 4; k++ )
cout << '*';
cout << endl;
} // end inner for
cout << endl;
} // end outer for
ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Exercise 5.26 Solution: ex05_26.cpp


// Prints 5 groups of 3 lines, each containing 4 asterisks.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
for ( int i = 1; i <= 5; i++ )
{
for ( int j = 1; j <= 3; j++ )
{
for ( int k = 1; k <= 4; k++ )
cout << '*';
cout << endl;
} // end inner for
cout << endl;
} // end outer for
return 0; // indicate successful termination
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

47

48

Chapter 5 Control Statements: Part 2

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

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

// Exercise 5.27 Solution: ex05_27.cpp


// Structured equivalent for continue statement.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
for ( int count = 1; count <= 10; count++ ) // loop 10 times
{
if ( count != 5 ) // if count == 5, skip to next iteration
cout << count << " ";
} // end for
cout << "\nUsed if condition to skip printing 5" << endl;
return 0; // indicate successful termination
} // end main

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

// Exercise 5.28 Solution: Twelve.h


// Definition of class Twelve that prints the 12 days of Christmas song.
// Member functions are defined in Twelve.cpp

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

// Exercise 5.28 Solution: Twelve.cpp


// Member-function definitions for class Twelve that
// prints the 12 days of Christmas song.
#include <iostream>
using std::cout;
using std::endl;

// Twelve class definition


class Twelve
{
public:
void printSong(); // print the 12 days of Christmas song
}; // end class Twelve

// include definition of class Twelve from Twelve.h


#include "Twelve.h"
// function to print the 12 days of Christmas song
void Twelve::printSong()
{
// loop 12 times
for ( int day = 1; day <= 12; day++ )
{
cout << "On the ";
// switch for current day
switch ( day )
{
case 1:
cout << "first";
break;
case 2:
cout << "second";
break;
case 3:
cout << "third";
break;
case 4:
cout << "fourth";
break;
case 5:

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

Chapter 5 Control Statements: Part 2

cout << "fifth";


break;
case 6:
cout << "sixth";
break;
case 7:
cout << "seventh";
break;
case 8:
cout << "eighth";
break;
case 9:
cout << "ninth";
break;
case 10:
cout << "tenth";
break;
case 11:
cout << "eleventh";
break;
case 12:
cout << "twelfth";
break;
} // end switch
cout << " day of Christmas,\nMy true love sent to me:\n";
// switch for gifts
switch ( day )
{
case 12:
cout << "\tTwelve drummers drumming,\n";
case 11:
cout << "\tEleven pipers piping,\n";
case 10:
cout << "\tTen lords a-leaping,\n";
case 9:
cout << "\tNine ladies dancing,\n";
case 8:
cout << "\tEight maids a-milking,\n";
case 7:
cout << "\tSeven swans a-swimming,\n";
case 6:
cout << "\tSix geese a-laying,\n";
case 5:
cout << "\tFive golden rings,\n";
case 4:
cout << "\tFour calling birds,\n";
case 3:
cout << "\tThree French hens,\n";
case 2:
cout << "\tTwo turtle doves, and\n";
case 1:
cout << "A partridge in a pear tree.\n\n\n";

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

// Exercise 5.28 Solution: ex05_28.cpp


// Create Twelve object, print the 12 days of Christmas song.
// include definition of class Twelve from Twelve.h
#include "Twelve.h"
int main()
{
Twelve application; // create Twelve object
application.printSong(); // print the 12 days of Christmas song
return 0; // indicate successful termination
} // end main

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.

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

Chapter 5 Control Statements: Part 2


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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

// Exercise 5.29 Solution: ex05_29.cpp


// Peter Minuit Problem:
// calculating compound interest with several interest rates.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setw; // enables program to set a field width
using std::setprecision;
#include <cmath> // standard C++ math library
using std::pow; // enables program to use function pow
int main()
{
double amount; // amount on deposit at end of each year
double principal = 24.0; // initial amount before interest
double rate; // interest rate
// set floating-point number format
cout << fixed << setprecision( 2 );
// loop through interest rates 5% to 10%
for ( int rate = 5; rate <= 10; rate++ )
{
// display headers
cout << "\nInterest rate: " << rate << "%\n"
<< "Year" << setw( 30 ) << "Amount on deposit" << endl;
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 379; year++ )
{
// calculate new amount for specified year
amount = principal * pow( 1.0 + rate / 100.0, year );
// display the year and the amount
cout << setw( 4 ) << year << setw( 30 ) << amount << endl;
} // end inner for
} // end outer for
return 0; // indicate successful termination
} // end main

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

You might also like