You are on page 1of 88

6

Form ever follows function.

Functions
and an
Introduction
to Recursion

Louis Henri Sullivan

E pluribus unum.
(One composed of many.)
Virgil

OBJECTIVES

O! call back yesterday, bid


time return.

In this chapter you will learn:

William Shakespeare

Call me Ishmael.

Herman Melville

When you call me that,


smile!

Owen Wister

Answer me in one word.

William Shakespeare

There is a point at which


methods devour themselves.

Frantz Fanon

Life can only be understood


backwards; but it must be
lived forwards.

Soren Kierkegaard

To construct programs modularly from functions.


To use common math functions available in the C++
Standard Library.
To create functions with multiple parameters.
The mechanisms for passing information between
functions and returning results.
How the function call/return mechanism is supported by
the function call stack and activation records.
To use random number generation to implement gameplaying applications.
How the visibility of identiers is limited to specic
regions of programs.
To write and use recursive functions, i.e., functions that
call themselves.

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

Chapter 6 Functions and an Introduction to Recursion

Self-Review Exercises
6.1

Answer each of the following:


a) Program components in C++ are called
and
.
ANS: functions, classes.
b) A function is invoked with a(n)
.
ANS: function call.
c) A variable that is known only within the function in which it is defined is called a(n)
.
ANS: local variable.
d) The
statement in a called function passes the value of an expression back
to the calling function.
ANS: return.
e) The keyword
is used in a function header to indicate that a function does
not return a value or to indicate that a function contains no parameters.
ANS: void.
f) The
of an identifier is the portion of the program in which the identifier
can be used.
ANS: scope.
g) The three ways to return control from a called function to a caller are
,
and
.
ANS: return;, return expression; or encounter the closing right brace of a function.
h) A(n)
allows the compiler to check the number, types and order of the arguments passed to a function.
ANS: function prototype.
i) Function
is used to produce random numbers.
ANS: rand.

j) Function

ANS: srand.

is used to set the random number seed to randomize a program.

k) The storage-class specifiers are mutable,


ANS: auto, register, extern, static.

and

l) Variables declared in a block or in the parameter list of a function are assumed to be of


storage class
unless specified otherwise.
ANS: auto.

m) Storage-class specifier
is a recommendation to the compiler to store a variable in one of the computers registers.
ANS: register.

n) A variable declared outside any block or function is a(n)


variable.
ANS: global.
o) For a local variable in a function to retain its value between calls to the function, it must
be declared with the
storage-class specifier.
ANS: static.

p) The six possible scopes of an identifier are


,
,
,
,
and
.
ANS: function scope, file scope, block scope, function-prototype scope, class scope,
namespace scope.
q) A function that calls itself either directly or indirectly (i.e., through another function)
is a(n)
function.
ANS: recursive.

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

Self-Review Exercises

r) A recursive function typically has two components: One that provides a means for the
recursion to terminate by testing for a(n)
case and one that expresses the
problem as a recursive call for a slightly simpler problem than the original call.
ANS: base.
s) In C++, it is possible to have various functions with the same name that operate on different types or numbers of arguments. This is called function
.
ANS: overloading.
enables access to a global variable with the same name as a variable in
t) The
the current scope.
ANS: unary scope resolution operator (::).
u) The
qualifier is used to declare read-only variables.
ANS: const.

v) A function
enables a single function to be defined to perform a task on
many different data types.
ANS: template.
6.2
For the program in Fig. 6.40, state the scope (either function scope, file scope, block scope
or function-prototype scope) of each of the following elements:
a) The variable x in main.
ANS: block scope.
b) The variable y in cube.
ANS: block scope.
c) The function cube.
ANS: file scope.
d) The function main.
ANS: file scope.
e) The function prototype for cube.
ANS: file scope.
f) The identifier y in the function prototype for cube.
ANS: function-prototype scope.

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

// Exercise 6.2: Ex06_02.cpp


#include <iostream>
using std::cout;
using std::endl;
int cube( int y ); // function prototype
int main()
{
int x;
for ( x = 1; x <= 10; x++ ) // loop 10 times
cout << cube( x ) << endl; // calculate cube of x and output results
return 0; // indicates successful termination
} // end main

Fig. 6.40 | Program for Exercise 6.2


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

4
18
19
20
21
22

Chapter 6 Functions and an Introduction to Recursion

// definition of function cube


int cube( int y )
{
return y * y * y;
} // end function cube

Fig. 6.40 | Program for Exercise 6.2


6.3
Write a program that tests whether the examples of the math library function calls shown
in Fig. 6.2 actually produce the indicated results.
ANS: See the following program:
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

// Exercise 6.3: Ex06_03.cpp


// Testing the math library functions.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include <cmath>
using namespace std;
int main()
{
cout << fixed << setprecision( 1 );
cout << "sqrt(" << 900.0 << ") = " << sqrt( 900.0 )
<< "\nsqrt(" << 9.0 << ") = " << sqrt( 9.0 );
cout << "\nexp(" << 1.0 << ") = " << setprecision( 6 )
<< exp( 1.0 ) << "\nexp(" << setprecision( 1 ) << 2.0
<< ") = " << setprecision( 6 ) << exp( 2.0 );
cout << "\nlog(" << 2.718282 << ") = " << setprecision( 1 )
<< log( 2.718282 )
<< "\nlog(" << setprecision( 6 ) << 7.389056 << ") = "
<< setprecision( 1 ) << log( 7.389056 );
cout << "\nlog10(" << 1.0 << ") = " << log10( 1.0 )
<< "\nlog10(" << 10.0 << ") = " << log10( 10.0 )
<< "\nlog10(" << 100.0 << ") = " << log10( 100.0 ) ;
cout << "\nfabs(" << 13.5 << ") = " << fabs( 13.5 )
<< "\nfabs(" << 0.0 << ") = " << fabs( 0.0 )
<< "\nfabs(" << -13.5 << ") = " << fabs( -13.5 );
cout << "\nceil(" << 9.2 << ") = " << ceil( 9.2 )
<< "\nceil(" << -9.8 << ") = " << ceil( -9.8 );
cout << "\nfloor(" << 9.2 << ") = " << floor( 9.2 )
<< "\nfloor(" << -9.8 << ") = " << floor( -9.8 );
cout << "\npow(" << 2.0 << ", " << 7.0 << ") = "
<< pow( 2.0, 7.0 ) << "\npow(" << 9.0 << ", "
<< 0.5 << ") = " << pow( 9.0, 0.5 );
cout << setprecision(3) << "\nfmod("

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

Self-Review Exercises
41
42
43
44
45
46
47

<< 13.675 << ", " << 2.333 << ") = "
<< fmod( 13.675, 2.333 ) << setprecision( 1 );
cout << "\nsin(" << 0.0 << ") = " << sin( 0.0 );
cout << "\ncos(" << 0.0 << ") = " << cos( 0.0 );
cout << "\ntan(" << 0.0 << ") = " << tan( 0.0 ) << endl;
return 0; // indicates successful termination
} // end main

sqrt(900.0) = 30.0
sqrt(9.0) = 3.0
exp(1.0) = 2.718282
exp(2.0) = 7.389056
log(2.718282) = 1.0
log(7.389056) = 2.0
log10(1.0) = 0.0
log10(10.0) = 1.0
log10(100.0) = 2.0
fabs(13.5) = 13.5
fabs(0.0) = 0.0
fabs(-13.5) = 13.5
ceil(9.2) = 10.0
ceil(-9.8) = -9.0
floor(9.2) = 9.0
floor(-9.8) = -10.0
pow(2.0, 7.0) = 128.0
pow(9.0, 0.5) = 3.0
fmod(13.675, 2.333) = 2.010
sin(0.0) = 0.0
cos(0.0) = 1.0
tan(0.0) = 0.0

6.4

Give the function header for each of the following functions:


a) Function hypotenuse that takes two double-precision, floating-point arguments, side1
and side2, and returns a double-precision, floating-point result.
ANS: double hypotenuse( double side1, double side2 )

b) Function smallest that takes three integers, x, y and z, and returns an integer.
ANS: int smallest( int x, int y, int z )

c) Function instructions that does not receive any arguments and does not return a value. [Note: Such functions are commonly used to display instructions to a user.]
ANS: void instructions( void ) // in C++ (void) can be written ()

d) Function intToDouble that takes an integer argument, number, and returns a doubleprecision, floating-point result.
ANS: double intToDouble( int number )

6.5

Give the function prototype for each of the following:


a) The function described in Exercise 6.4(a).
ANS: double hypotenuse( double, double );

b) The function described in Exercise 6.4(b).


ANS: int smallest( int, int, int );

c) The function described in Exercise 6.4(c).


ANS: void instructions( void ); // in C++ (void) can be written ()

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

Chapter 6 Functions and an Introduction to Recursion


d) The function described in Exercise 6.4(d).
ANS: double intToDouble( int );

6.6

Write a declaration for each of the following:


a) Integer count that should be maintained in a register. Initialize count to 0.
ANS: register int count = 0;

b) Double-precision, floating-point variable lastVal that is to retain its value between calls
to the function in which it is defined.
ANS: static double lastVal;

6.7
Find the error in each of the following program segments, and explain how the error can be
corrected (see also Exercise 6.53):
a) int g( void )
{
cout << "Inside function g" << endl;
int h( void )
{
cout << "Inside function h" << endl;
}
}

ANS: Error: Function h is defined in function g.

b)

Correction: Move the definition of h out of the definition of g.

int sum( int x, int y )


{
int result;
result = x + y;
}

ANS: Error: The function is supposed to return an integer, but does not.

Correction: Delete variable result and place the following statement in the function:
return x + y;

c)

int sum( int n )


{
if ( n == 0 )
return 0;
else
n + sum( n - 1 );
}

ANS: Error: The result of n + sum( n - 1 ) is not returned; sum returns an improper result.

Correction: Rewrite the statement in the else clause as


return n + sum( n - 1 );

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

Self-Review Exercises
d)

void f( double a );
{
float a;
cout << a << endl;
}

ANS: Errors: Semicolon after the right parenthesis that encloses the parameter list, and re-

e)

defining the parameter a in the function definition.


Corrections: Delete the semicolon after the right parenthesis of the parameter list,
and delete the declaration float a;.

void product( void )


{
int a;
int b;
int c;
int result;
cout << "Enter three integers: ";
cin >> a >> b >> c;
result = a * b * c;
cout << "Result is " << result;
return result;
}

ANS: Error: The function returns a value when it is not supposed to.

Correction: Eliminate the return statement.

6.8

Why would a function prototype contain a parameter type declaration such as double &?
ANS: This creates a reference parameter of type reference to double that enables the function to modify the original variable in the calling function.

6.9

(True/False) All arguments to function calls in C++ are passed by value.


ANS: False. C++ enables pass-by-reference using reference parameters (and pointers, as we
discuss in Chapter 8).

6.10 Write a complete program that prompts the user for the radius of a sphere, and calculates
and prints the volume of that sphere. Use an inline function sphereVolume that returns the result
of the following expression: ( 4.0 / 3.0 ) * 3.14159 * pow( radius, 3 ).
ANS: See the following program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// Exercise 6.10 Solution: Ex06_10.cpp


// Inline function that calculates the volume of a sphere.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
using std::pow;
const double PI = 3.14159; // define global constant PI
// calculates volume of a sphere
inline double sphereVolume( const double radius )
{
return 4.0 / 3.0 * PI * pow( radius, 3 );

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

8
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Chapter 6 Functions and an Introduction to Recursion

} // end inline function sphereVolume


int main()
{
double radiusValue;
// prompt user for radius
cout << "Enter the length of the radius of your sphere: ";
cin >> radiusValue; // input radius
// use radiusValue to calculate volume of sphere and display result
cout << "Volume of sphere with radius " << radiusValue
<< " is " << sphereVolume( radiusValue ) << endl;
return 0; // indicates successful termination
} // end main

Enter the length of the radius of your sphere: 10


Volume of sphere with radius 10 is 4188.79

Exercises
6.11

Show the value of x after each of the following statements is performed:


a) x = fabs( 7.5 )
ANS: 7.5
b) x = floor( 7.5 )
ANS: 7.0
c) x = fabs( 0.0 )
ANS: 0.0
d) x = ceil( 0.0 )
ANS: 0.0
e) x = fabs( -6.4 )
ANS: 6.4
f) x = ceil( -6.4 )
ANS: -6.0
g) x = ceil( -fabs( -8 + floor( -5.5 ) ) )
ANS: -14.0

6.12 A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage
charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24
hours at a time. Write a program that calculates and prints the parking charges for each of three
customers who parked their cars in this garage yesterday. You should enter the hours parked for each
customer. Your program should print the results in a neat tabular format and should calculate and

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

Exercises

print the total of yesterdays receipts. The program should use the function calculateCharges to
determine the charge for each customer. Your outputs should appear in the following format:
Car
1
2
3
TOTAL

Hours
1.5
4.0
24.0
29.5

Charge
2.00
2.50
10.00
14.50

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

// Exercise 6.12 Solution: Ex06_12.cpp


// Calculate charges for 3 cars at parking garage.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
using std::setw;
#include <cmath>
using std::ceil;
double calculateCharges( double ); // function prototype
int main()
{
double hour; // number of hours for current car
double currentCharge; // parking charge for current car
double totalCharges = 0.0; // total charges
double totalHours = 0.0; // total number of hours
int first = 1; // used for printing table headers
cout << fixed; // set floating-point number format
cout << "Enter the hours parked for 3 cars: ";
// loop 3 times for 3 cars
for ( int i = 1; i <= 3; i++ )
{
cin >> hour;
totalHours += hour; // add current hours to total hours
// if first time through loop, display headers
if ( first )
{
cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"
<< setw( 15 ) << "Charge\n";
first = 0; // set first to 0 to prevent from printing again
} // end if

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

10
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

Chapter 6 Functions and an Introduction to Recursion

// calculate current car's parking charge


currentCharge = calculateCharges( hour );
totalCharges += currentCharge; // update total charges
// display row data for current car
cout << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour
<< setw( 14 ) << setprecision( 2 ) << currentCharge << "\n";
} // end for
// display row data for totals
cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )
<< totalHours << setw( 14 ) << setprecision( 2 )
<< totalCharges << endl;
return 0; // indicate successful termination
} // end main
// calculateCharges returns charge according to number of hours
double calculateCharges( double hours )
{
double charge; // calculated charge
if ( hours < 3.0 ) // $2 for up to 3 hours
charge = 2.0;
else if ( hours < 24.0 ) // $.50 for each extra hour
charge = 2.0 + .5 * ceil( hours - 3.0 );
else // maximum charge $10
charge = 10.0;
return charge; // return calculated charge
} // end function calculateCharges

Enter the hours parked for 3 cars: 1.5 4.0 24.0


Car
Hours
Charge
1
1.5
2.00
2
4.0
2.50
3
24.0
10.00
TOTAL
29.5
14.50

6.13

An application of function floor is rounding a value to the nearest integer. The statement
y = floor( x + .5 );

rounds the number x to the nearest integer and assigns the result to y. Write a program that reads
several numbers and uses the preceding statement to round each of these numbers to the nearest
integer. For each number processed, print both the original number and the rounded number.
ANS:

1
2
3
4

// Exercise 6.13 Solution: Ex06_13.cpp


// Rounding numbers using floor.
#include <iostream>
using std::cin;

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

Exercises
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

11

using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include <cmath>
using std::floor;
void roundToIntegers( void ); // function prototype
int main()
{
roundToIntegers(); // call function roundToIntegers
return 0; // indicate successful termination
} // end main
// roundToIntegers rounds 5 inputs
void roundToIntegers( void )
{
double x; // current input
double y; // current input rounded
cout << fixed; // set floating-point number format
// loop for 5 inputs
for ( int loop = 1; loop <= 5; loop++ )
{
cout << "Enter a number: ";
cin >> x;
y = floor( x + .5 ); // y holds rounded input
cout << setprecision( 6 ) << x << " rounded is "
<< setprecision( 1 ) << y << endl;
} // end for
} // end function roundToIntegers

Enter a number: 8.22


8.220000 rounded is 8.0
Enter a number: 7.98
7.980000 rounded is 8.0
Enter a number: 4.52
4.520000 rounded is 5.0
Enter a number: 6.9999
6.999900 rounded is 7.0
Enter a number: 3.345
3.345000 rounded is 3.0

6.14

Function floor can be used to round a number to a specific decimal place. The statement
y = floor( x * 10 + .5 ) / 10;

rounds x to the tenths position (the rst position to the right of the decimal point). The statement

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

12

Chapter 6 Functions and an Introduction to Recursion


y = floor( x * 100 + .5 ) / 100;

rounds x to the hundredths position (the second position to the right of the decimal point). Write
a program that denes four functions to round a number x in various ways:
a) roundToInteger( number )
b) roundToTenths( number )
c) roundToHundredths( number )
d) roundToThousandths( number )
For each value read, your program should print the original value, the number rounded to the
nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.
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

// Exercise 6.14 Solution: Ex06_14.cpp


// Round numbers to integers, tenths, hundredths and thousandths.
#include <iostream>
using std::cin;
using std::cout;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include <cmath>
using std::floor;
double
double
double
double

roundToInteger( double ); // function prototype


roundToTenths( double ); // function prototype
roundToHundredths( double ); // function prototype
roundToThousandths( double ); // function prototype

int main()
{
int count; // number of values to process
double number; // current input
cout << "How many numbers do you want to process? " << fixed;
cin >> count;
// loop for inputs
for ( int i = 0; i < count; i++ )
{
cout << "\nEnter number: ";
cin >> number;
// display number rounded to nearest integer
cout << setprecision( 6 ) << number
<< " rounded to the nearest integer is:
"
<< setprecision( 0 ) << roundToInteger( number ) << '\n';
// display number rounded to nearest tenth
cout << setprecision( 6 ) << number
<< " rounded to the nearest tenth is:

"

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

Exercises
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

13

<< setprecision( 1 ) << roundToTenths( number ) << '\n';


// display number rounded to nearest hundredth
cout << setprecision( 6 ) << number
<< " rounded to the nearest hundredth is: "
<< setprecision( 2 ) << roundToHundredths( number ) << '\n';
// display number rounded to nearest thousandth
cout << setprecision( 6 ) << number
<< " rounded to the nearest thousandth is: "
<< setprecision( 3 ) << roundToThousandths( number ) << '\n';
} // end for
return 0; // indicate successful termination
} // end main
// roundToInteger rounds n to nearest integer
double roundToInteger( double n )
{
return floor( n + .5 );
} // end function roundToInteger
// roundToTenths rounds n to nearest tenth
double roundToTenths( double n )
{
return floor( n * 10 + .5 ) / 10;
} // end function roundToTenths
// roundToHundredths rounds n to nearest hundredth
double roundToHundredths( double n )
{
return floor( n * 100 + .5 ) / 100;
} // end function roundToHundredths
// roundToThousandths rounds n to nearest thousandth
double roundToThousandths( double n )
{
return floor( n * 1000 + .5 ) / 1000;
} // end function roundToThousandths

How many numbers do you want to process? 1


Enter number: 3.4158
3.415800 rounded to the
3.415800 rounded to the
3.415800 rounded to the
3.415800 rounded to the

6.15

nearest
nearest
nearest
nearest

integer is:
tenth is:
hundredth is:
thousandth is:

3
3.4
3.42
3.416

Answer each of the following questions:


a) What does it mean to choose numbers at random?
ANS: Every number has an equal chance of being chosen at any time.

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

14

Chapter 6 Functions and an Introduction to Recursion


b) Why is the rand function useful for simulating games of chance?
ANS: Because it produces a sequence of pseudo-random numbers that when scaled appear
to be random.
c) Why would you randomize a program by using srand? Under what circumstances is it
desirable not to randomize?
ANS: The sequence of numbers produced by the random number generator differ each
time function srand is called. Not randomizing is useful for debugging purposes
the programmer knows the sequence of numbers.
d) Why is it often necessary to scale or shift the values produced by rand?
ANS: To produce random values in a specific range.
e) Why is computerized simulation of real-world situations a useful technique?
ANS: It enables more accurate predictions of random events such as cars arriving at a toll
booth, people arriving in lines, birds arriving at a tree, etc. The results of a simulation
can help determine how many toll booths to have open or how many cashiers to have
open at specified times.

6.16

Write statements that assign random integers to the variable n in the following ranges:
a) 1 n 2
ANS: n = 1 + rand() % 2;

b) 1 n 100

ANS: n = 1 + rand() % 100;

c) 0 n 9

ANS: n = rand() % 10;

d) 1000 n 1112

ANS: n = 1000 + rand() % 13;

e) 1 n 1

ANS: n = rand() % 3 - 1;

f) 3 n 11

ANS: n = rand() % 15 - 3;

6.17 For each of the following sets of integers, write a single statement that prints a number at
random from the set:
a) 2, 4, 6, 8, 10.
ANS: cout << 2 * ( 1 + rand() % 5 ) ) << \n;

b) 3, 5, 7, 9, 11.

ANS: cout << 1 + 2 * ( 1 + rand() % 5 ) ) << \n;

c) 6, 10, 14, 18, 22.

ANS: cout << 6 + 4 * ( rand() % 5 ) << \n;

6.18

Write a function integerPower( base, exponent ) that returns the value of


base exponent

For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer and that base is an integer. The function integerPower should use for or while to control the calculation. Do not use any math library functions.
ANS:

1
2
3
4

// Exercise 6.18 Solution: Ex06_18.cpp


// Calculate exponentiation of integers.
#include <iostream>
using std::cin;

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

Exercises
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

15

using std::cout;
using std::endl;
int integerPower( int, int ); // function prototype
int main()
{
int exp; // integer exponent
int base; // integer base
cout << "Enter base and exponent: ";
cin >> base >> exp;
cout << base << " to the power " << exp << " is: "
<< integerPower( base, exp ) << endl;
return 0; // indicate successful termination
} // end main
// integerPower calculates and returns b raised to the e power
int integerPower( int b, int e )
{
int product = 1; // resulting product
// multiply product times b e number of times
for ( int i = 1; i <= e; i++ )
product *= b;
return product; // return resulting product
} // end function integerPower

Enter base and exponent: 5 2


5 to the power 2 is: 25

6.19 (Hypotenuse) Define a function hypotenuse that calculates the length of the hypotenuse of
a right triangle when the other two sides are given. Use this function in a program to determine the
length of the hypotenuse for each of the triangles shown below. The function should take two double arguments and return the hypotenuse as a double.

Triangle

Side 1

Side 2

3.0

4.0

5.0

12.0

8.0

15.0

ANS:

1
2
3

// Exercise 6.19 Solution: Ex06_19.cpp


// Calculate hypotenuse value for a right triangle
// given values for two sides.

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

16
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

Chapter 6 Functions and an Introduction to Recursion

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include <cmath>
using std::sqrt;
double hypotenuse( double, double ); // function prototype
int main()
{
double side1; // value for first side
double side2; // value for second side
cout << fixed; // set floating-point number format
// loop 3 times
for ( int i = 1; i <= 3; i++ )
{
cout << "\nEnter 2 sides of right triangle: ";
cin >> side1 >> side2;
// calculate and display hypotenuse value
cout << "Hypotenuse: " << setprecision( 1 )
<< hypotenuse( side1, side2 ) << endl;
} // end for
return 0; // indicate successful termination
} // end main
// hypotenuse calculates value of hypotenuse of
// a right triangle given two side values
double hypotenuse( double s1, double s2 )
{
return sqrt( s1 * s1 + s2 * s2 );
} // end function hypotenuse

Enter 2 sides of right triangle: 3.0 4.0


Hypotenuse: 5.0
Enter 2 sides of right triangle: 5.0 12.0
Hypotenuse: 13.0
Enter 2 sides of right triangle: 8.0 15.0
Hypotenuse: 17.0

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

Exercises

17

6.20 Write a function multiple that determines for a pair of integers whether the second is a
multiple of the first. The function should take two integer arguments and return true if the second
is a multiple of the first, false otherwise. Use this function in a program that inputs a series of pairs
of integers.
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

// Exercise 6.20 Solution: Ex06_20.cpp


// Determines whether, for a pair of integers,
// the second is a multiple of the first.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
bool multiple( int, int ); // function prototype
int main()
{
int x; // first integer
int y; // second integer
// loop 3 times
for ( int i = 1; i <= 3; i++ )
{
cout << "Enter two integers: ";
cin >> x >> y;
// determine if second is multiple of first
if ( multiple( x, y ) )
cout << y << " is a multiple of " << x << "\n\n";
else
cout << y << " is not a multiple of " << x << "\n\n";
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main
// multiple determines if b is multiple of a
bool multiple( int a, int b )
{
return !( b % a );
} // end function multiple

Enter two integers: 3 4


4 is not a multiple of 3
Enter two integers: 12 3
3 is not a multiple of 12
Enter two integers: 3 12
12 is a multiple of 3

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

18

Chapter 6 Functions and an Introduction to Recursion

6.21 Write a program that inputs a series of integers and passes them one at a time to function
even, which uses the modulus operator to determine whether an integer is even. The function
should take an integer argument and return true if the integer is even and false otherwise.
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

// Exercise 6.21 Solution: Ex06_21.cpp


// Determine whether inputs are odd or even.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
bool isEven( int ); // function prototype
int main()
{
int x; // current input
// loop for 3 inputs
for ( int i = 1; i <= 3; i++ )
{
cout << "Enter an integer: ";
cin >> x;
// determine if input is even
if ( isEven( x ) )
cout << x << " is an even integer\n\n";
else
cout << x << " is an odd integer\n\n";
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main
// isEven returns true if a is even
bool isEven( int a )
{
return !( a % 2 );
} // end function isEven

Enter an integer: 8
8 is an even integer
Enter an integer: 3
3 is an odd integer
Enter an integer: 99
99 is an odd integer

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

Exercises

19

6.22 Write a function that displays at the left margin of the screen a solid square of asterisks
whose side is specified in integer parameter side. For example, if side is 4, the function displays the
following:
****
****
****
****

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

// Exercise 6.22 Solution: Ex06_22.cpp


// Displays a solid square of asterisks.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void square( int ); // function prototype
int main()
{
int side; // input side length
cout << "Enter side: ";
cin >> side;
cout << '\n';
square( side ); // display solid square of asterisks
cout << endl;
return 0; // indicate successful termination
} // end main
// square displays solid square of asterisks with specified side
void square( int side )
{
// loop side times for number of rows
for ( int row = 1; row <= side; row++ )
{
// loop side times for number of columns
for ( int col = 1; col <= side; col++ )
cout << '*';
cout << '\n';
} // end for
} // end function square

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

20

Chapter 6 Functions and an Introduction to Recursion

Enter side: 4
****
****
****
****

6.23 Modify the function created in Exercise 6.22 to form the square out of whatever character
is contained in character parameter fillCharacter. Thus, if side is 5 and fillCharacter is #, then
this function should print the following:
#####
#####
#####
#####
#####

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

// Exercise 6.23 Solution: Ex06_23.cpp


// Displays a solid square of input character.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void square( int, char ); // function prototype
int main()
{
int side; // input side length
char character; // fill character
cout << "Enter a character and the side length: ";
cin >> character >> side;
cout << '\n';
square( side, character ); // display solid square of input character
cout << endl;
return 0; // indicate successful termination
} // end main
// square displays solid square of fillCharacter with specified side
void square( int side, char fillCharacter )
{
// loop side times for number of rows
for ( int row = 1; row <= side; row++ )
{
// loop side times for number of columns
for ( int col = 1; col <= side; col++ )
cout << fillCharacter;

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

Exercises
33
34
35
36

21

cout << '\n';


} // end for
} // end function square

Enter a character and the side length: # 5


#####
#####
#####
#####
#####

6.24 Use techniques similar to those developed in Exercise 6.22 and Exercise 6.23 to produce a
program that graphs a wide range of shapes.
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

// Exercise 6.24 Solution: Ex06_24.cpp


// Graph a range of shapes.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
using std::sqrt;
void
void
void
void

square( int, char ); // function prototype


diamond( int, char ); // function prototype
triangle ( int, char ); // function prototype
circle( int, char ); // function prototype

int main()
{
int size; // input side length
char character; // fill character
int shape; // 1: square, 2: diamond, 3: triangle, 4: circle
cout << "Choose the shape to graph" << endl
<< "1 for square" << endl << "2 for diamond" << endl
<< "3 for triangle, " << endl << "4 for circle: " << endl << "? ";
cin >> shape;
cout << "Enter a character and size: ";
cin >> character >> size;
cout << '\n';
// display chosen shape using input character and size
switch( shape )
{
case 1: // square
square( size, character );

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

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

Chapter 6 Functions and an Introduction to Recursion

break;
case 2: // diamond
diamond( size, character );
break;
case 3: // triangle
triangle( size, character );
break;
case 4: // circle
circle( size, character );
break;
default: // default to square
square( size, character );
break;
} // end switch
cout << endl;
return 0; // indicate successful termination
} // end main
// square displays solid square of fillCharacter with specified side
void square( int side, char fillCharacter )
{
// loop side times for number of rows
for ( int row = 1; row <= side; row++ )
{
// loop side times for number of columns
for ( int col = 1; col <= side; col++ )
cout << fillCharacter;
cout << endl;
} // end for
cout << endl;
} // end function square
// diamond displays solid diamond of fillCharacter
// with specified number of rows
void diamond( int size, char fillCharacter )
{
int rows;
// top half
for ( rows = 1; rows <= size - 2; rows += 2 )
{
// print preceding spaces
for ( int space = ( size - rows ) / 2; space > 0; space-- )
cout << ' ';
// print characters
for ( int character = 1; character <= rows; character++ )
cout << fillCharacter;
cout << endl;
} // end for

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

Exercises
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
139
140
141
142
143

23

// bottom half
for ( rows = size; rows >= 0; rows -= 2 )
{
// print preceding spaces
for ( int space = ( size - rows ) / 2; space > 0; space-- )
cout << ' ';
// print characters
for ( int character = 1; character <= rows; character++ )
cout << fillCharacter;
cout << endl;
} // end for
cout << endl;
} // end function diamond
// triangle displays solid triangle of fillCharacter
// with specified number of rows
void triangle( int size, char fillCharacter )
{
// display triangle
for ( int row = 1; row <= size; row++ )
{
// print preceding spaces
for ( int space = size - row; space > 0; space-- )
cout << ' ';
// print characters
for ( int character = 1; character < 2 * row; character++ )
cout << fillCharacter;
cout << endl;
} // end for
cout << endl;
} // end function triangle
// circle displays solid circle of fillCharacter with specified radius
void circle( int radius, char fillCharacter )
{
double distance; // distance from current position to center
double vertical; // vertical distance from current position to center
double horizontal; // horizontal distance from current position to ctr
// loop for rows
for ( int row = 0; row <= 2 * radius + 1; row++ )
{
// loop for columns
for ( int col = 0; col <= 2 * radius + 1; col++ )
{
// calculate vertical and horizontal distances
vertical = radius - row;

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

24

Chapter 6 Functions and an Introduction to Recursion

144
horizontal = radius - col;
145
146
// calculate overall distance to center
147
distance = sqrt( vertical * vertical + horizontal * horizontal );
148
149
// if within radius of center
150
if ( distance <= radius )
151
cout << fillCharacter;
152
else
153
cout << ' ';
154
} // end for
155
156
cout << endl;
157
} // end for
158
159
cout << endl;
160 } // end function circle
Choose the shape to graph
1 for square
2 for diamond
3 for triangle,
4 for circle:
? 3
Enter a character and size: ^ 6
^
^^^
^^^^^
^^^^^^^
^^^^^^^^^
^^^^^^^^^^^

6.25

Write program segments that accomplish each of the following:


a) Calculate the integer part of the quotient when integer a is divided by integer b.
b) Calculate the integer remainder when integer a is divided by integer b.
c) Use the program pieces developed in (a) and (b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should print as follows:
6

ANS:

1
2
3
4
5
6

// Exercise 6.25 Solution: Ex06_25.cpp


// Print input number as series of digits,
// each pair of which is separated by two spaces.
#include <iostream>
using std::cin;
using std::cout;

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

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

using std::endl;
int quotient( int, int ); // function prototype
int remainder( int, int ); // function prototype
int main()
{
int number; // input number
int divisor = 10000; // current divisor
cout << "Enter an integer between 1 and 32767: ";
cin >> number;
cout << "The digits in the number are:\n";
// determine and print each digit
while ( number >= 1 )
{
// if number is >= current divisor, determine digit
if ( number >= divisor )
{
// use quotient to determine current digit
cout << quotient( number, divisor ) << " ";
// update number to be remainder
number = remainder( number, divisor );
// update divisor for next digit
divisor = quotient( divisor, 10 );
} // end for
else // if number < current divisor, no digit
divisor = quotient( divisor, 10 );
} // end while
cout << endl;
return 0; // indicate successful termination
} // end main
// Part A: determine quotient using integer division
int quotient( int a, int b )
{
return a / b;
} // end function quotient
// Part B: determine remainder using the modulus operator
int remainder( int a, int b )
{
return a % b;
} // end function remainder

Enter an integer between 1 and 32767: 4562


The digits in the number are:
4 5 6 2

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

25

26

Chapter 6 Functions and an Introduction to Recursion

6.26 Write a function that takes the time as three integer arguments (hours, minutes and seconds) and returns the number of seconds since the last time the clock struck 12. Use this function
to calculate the amount of time in seconds between two times, both of which are within one 12hour cycle of the clock.
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

// Exercise 6.26 Solution: Ex06_26.cpp


// Calculate amount of time in seconds between two times.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
using std::fabs;
unsigned seconds( unsigned, unsigned, unsigned ); // function prototype
int main()
{
int hours; // current time's hours
int minutes; // current time's minutes
int secs; // current time's seconds
double first; // first time, in seconds
double second; // second time, in seconds
double difference; // difference between two times, in seconds
cout << "Enter the first time as three integers: ";
cin >> hours >> minutes >> secs;
first = seconds( hours, minutes, secs ); // calculate first time
cout << "Enter the second time as three integers: ";
cin >> hours >> minutes >> secs;
second = seconds( hours, minutes, secs ); // calculate second time
difference = fabs( first - second ); // calculate difference
// display difference
cout << "The difference between the times is "
<< difference << " seconds" << endl;
return 0; // indicate successful termination
} // end main
// seconds returns number of seconds since clock "struck 12"
// given input time as hours h, minutes m, seconds s
unsigned seconds( unsigned h, unsigned m, unsigned s )
{
return 3600 * ( h >= 12 ? h - 12 : h ) + 60 * m + s;
} // end function seconds

Enter the first time as three integers: 5 33 45


Enter the second time as three integers: 9 22 8
The difference between the times is 13703 seconds

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

Exercises
6.27

27

(Celsius and Fahrenheit Temperatures) Implement the following integer functions:


a) Function celsius returns the Celsius equivalent of a Fahrenheit temperature.
b) Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature.
c) Use these functions to write a program that prints charts showing the Fahrenheit equivalents of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of
all Fahrenheit temperatures from 32 to 212 degrees. Print the outputs in a neat tabular
format that minimizes the number of lines of output while remaining readable.
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 6.27 Solution: Ex06_27.cpp


// Fahrenheit and Celsius equivalents.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int celsius( int ); // function prototype
int fahrenheit( int ); // function prototype
int main()
{
// display table of Fahrenheit equivalents of Celsius temperatures
cout << "Fahrenheit equivalents of Celsius temperatures:" << endl;
// create 4 sets of table headers
for ( int t = 0; t < 4; t++ )
cout << setw( 7 ) << "Celsius" << setw( 12 ) << "Fahrenheit ";
cout << endl;
// display temperatures in blocks of 25
for ( int i = 0; i < 25; i++ )
{
for ( int j = 0; j <= 75; j += 25 )
cout << setw( 7 ) << i + j
<< setw( 11 ) << fahrenheit( i + j ) << ' ';
cout << endl;
} // end for
// display equivalent for 100
cout << setw( 64 ) << 100 << setw( 11 ) << fahrenheit( 100 ) << endl;
// display table of Celsius equivalents of Fahrenheit temperatures
cout << "\nCelsius equivalents of Fahrenheit temperatures:" << endl;
// create 4 sets of table headers
for ( int t = 0; t < 4; t++ )
cout << setw( 10 ) << "Fahrenheit" << setw( 9 ) << "Celsius ";
cout << endl;

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

28
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

Chapter 6 Functions and an Introduction to Recursion

// display temperatures in blocks of 45


for ( int i = 32; i < 77; i++ )
{
for ( int j = 0; j <= 135; j += 45 )
cout << setw( 10 ) << i + j
<< setw( 8 ) << celsius( i + j ) << ' ';
cout << endl;
} // end for
// display equivalent for 212
cout << setw( 67 ) << 212 << setw( 8 ) << celsius( 212 ) << endl;
return 0; // indicate successful termination
} // end main
// celsius returns Celsius equivalent of fTemp,
// given in Fahrenheit
int celsius( int fTemp )
{
return static_cast< int > ( 5.0 / 9.0 * ( fTemp - 32 ) );
} // end function celsius
// fahrenheit returns Fahrenheit equivalent of cTemp,
// given in Celsius
int fahrenheit( int cTemp )
{
return static_cast< int > ( 9.0 / 5.0 * cTemp + 32 );
} // end function fahrenheit

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

Exercises

29

Fahrenheit equivalents of Celsius temperatures:


Celsius Fahrenheit Celsius Fahrenheit Celsius Fahrenheit Celsius Fahrenheit
0
32
25
77
50
122
75
167
1
33
26
78
51
123
76
168
2
35
27
80
52
125
77
170
3
37
28
82
53
127
78
172
4
39
29
84
54
129
79
174
5
41
30
86
55
131
80
176
6
42
31
87
56
132
81
177
7
44
32
89
57
134
82
179
8
46
33
91
58
136
83
181
9
48
34
93
59
138
84
183
10
50
35
95
60
140
85
185
...
Celsius equivalents of Fahrenheit temperatures:
Fahrenheit Celsius Fahrenheit Celsius Fahrenheit Celsius Fahrenheit Celsius
32
0
77
25
122
50
167
75
33
0
78
25
123
50
168
75
34
1
79
26
124
51
169
76
35
1
80
26
125
51
170
76
36
2
81
27
126
52
171
77
37
2
82
27
127
52
172
77
38
3
83
28
128
53
173
78
39
3
84
28
129
53
174
78
40
4
85
29
130
54
175
79
...

6.28 Write a program that inputs three double-precision, floating-point numbers and passes
them to a function that returns the smallest number.
ANS:

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

// Exercise 6.28 Solution: Ex06_28.cpp


// Determine the smallest of 3 numbers.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
double smallest( double, double, double ); // function prototype
int main()
{
double x; // first input
double y; // second input
double z; // third input
cout << "Enter three numbers: ";
cin >> x >> y >> z;
// determine smallest value
cout << "The smallest value is " << smallest( x, y, z ) << endl;
return 0; // indicate successful termination
} // end main

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

30
23
24
25
26
27
28
29
30
31
32
33

Chapter 6 Functions and an Introduction to Recursion

// smallest returns the smallest of a, b and c


double smallest( double a, double b, double c )
{
if ( a < b && a < c )
return a;
else if ( b < a && b < c )
return b;
else
return c;
} // end function smallest

Enter three numbers: 6.77 4.3 9.65


The smallest value is 4.3

6.29 (Perfect Numbers) An integer is said to be a perfect number if the sum of its factors, including
1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, because
6 = 1 + 2 + 3. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1
and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect.
Challenge the power of your computer by testing numbers much larger than 1000.
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 6.29 Solution: Ex06_29.cpp


// Determine perfect numbers between 1 and 1000.
// A number is perfect if it is equal to the sum of its factors.
#include <iostream>
using std::cout;
using std::endl;
bool isPerfect( int ); // function prototype
void printSum( int ); // function prototype
int main()
{
cout << "Perfect integers between 1 and 1000:" << endl;
// loop from 2 to 1000
for ( int j = 2; j <= 1000; j++ )
{
// if current integer is perfect
if ( isPerfect( j ) )
printSum( j ); // print it as sum of factors
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main
// isPerfect returns true if value is perfect integer,
// i.e., if value is equal to sum of its factors
bool isPerfect( int value )

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

Exercises
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

31

int factorSum = 1; // current sum of factors


// loop through possible factor values
for ( int i = 2; i <= value / 2; i++ )
{
// if i is factor
if ( value % i == 0 )
factorSum += i; // add to sum
} // end for

// return true if value is equal to sum of factors


return factorSum == value ? true : false;
} // end function isPerfect
// printSum displays value followed by factors in summation form
void printSum( int value )
{
cout << value << " = 1";
// loop through possible factor values
for ( int i = 2; i <= value / 2; i++ )
{
// if i is factor
if ( value % i == 0 )
cout << " + " << i; // display as part of sum
} // end for
cout << endl;
} // end function printSum

Perfect integers between 1 and 1000:


6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248

6.30 (PrimeNumbers) An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a program that determines and prints all the prime numbers between 2 and 10,000. How many of these numbers do you really have to test before being sure that you have found all the primes?
c) Initially, you might think that n/2 is the upper limit for which you must test to see
whether a number is prime, but you need only go as high as the square root of n. Why?
Rewrite the program, and run it both ways. Estimate the performance improvement.
ANS:

1
2
3
4

// Exercise 6.30 Part A and B Solution: Ex06_30.cpp


// Testing for prime numbers.
#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
47
48
49
50

Chapter 6 Functions and an Introduction to Recursion

using std::endl;
#include <iomanip>
using std::setw;
bool isPrime( int ); // function prototype
int main()
{
int count = 0;

// total number of primes found

cout << "The prime numbers from 1 to 10000 are:" << endl;
count++;
cout << setw( 6 ) << 2; // 2 is only even prime
// loop through odd numbers; even numbers > 2 cannot be prime
for ( int loop = 3; loop < 10000; loop += 2 )
{
if ( isPrime( loop ) ) // if current number prime
{
count++;
cout << setw( 6 ) << loop;
if ( count % 10 == 0 ) // new line after 10 values displayed
cout << '\n';
} // end if
} // end for
cout << endl << "Total of " << count
<< " prime numbers between 1 and 10000." << endl;
return 0; // indicate successful termination
} // end main
// isPrime returns true if n is prime
bool isPrime( int n )
{
// loop through possible factors
for ( int loop2 = 2; loop2 <= n / 2; loop2++ )
{
// if factor found, not prime
if ( n % loop2 == 0 )
return false;
} // end for
return true;
} // end function isPrime

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

Exercises

The prime numbers from 1 to 10000 are:


2
3
5
7
11
13
17
19
31
37
41
43
47
53
59
61
73
79
83
89
97
101
103
107
127
131
137
139
149
151
157
163
179
181
191
193
197
199
211
223
233
239
241
251
257
263
269
271
283
293
307
311
313
317
331
337
353
359
367
373
379
383
389
397
419
421
431
433
439
443
449
457
...
9739 9743 9749 9767 9769 9781 9787 9791
9817 9829 9833 9839 9851 9857 9859 9871
9901 9907 9923 9929 9931 9941 9949 9967
Total of 1229 prime numbers between 1 and 10000.

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

23
67
109
167
227
277
347
401
461

29
71
113
173
229
281
349
409
463

9803
9883
9973

9811
9887

// Exercise 6.30 Part C Solution: Ex06_30.cpp


// Testing for prime numbers.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <cmath>
using std::sqrt;
bool isPrime( int ); // function prototype
int main()
{
int count = 0; // total number of primes found
cout << "The prime numbers from 1 to 10000 are:" << endl;
count++;
cout << setw( 6 ) << 2; // 2 is only even prime
// loop through odd numbers; even numbers > 2 cannot be prime
for ( int loop = 3; loop < 10000; loop += 2 )
{
// if current number prime
if ( isPrime( loop ) )
{
count++;
cout << setw( 6 ) << loop;
// new line after 10 values displayed
if ( count % 10 == 0 )
cout << '\n';
} // end if
} // end for

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

33

34
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

Chapter 6 Functions and an Introduction to Recursion

cout << endl << "Total of " << count


<< " prime numbers between 1 and 10000." << endl;
return 0; // indicate successful termination
} // end main
// isPrime returns true if n is prime
bool isPrime( int n )
{
// loop through possible factors
for ( int i = 2;
i <= static_cast< int > ( sqrt( static_cast< double > ( n ) ) );
i++ )
{
// if factor found, not prime
if ( n % i == 0 )
return false;
} // end for
return true;
} // end function prime

The prime numbers from 1 to 10000 are:


2
3
5
7
11
13
17
19
31
37
41
43
47
53
59
61
73
79
83
89
97
101
103
107
127
131
137
139
149
151
157
163
179
181
191
193
197
199
211
223
233
239
241
251
257
263
269
271
283
293
307
311
313
317
331
337
353
359
367
373
379
383
389
397
419
421
431
433
439
443
449
457
...
9739 9743 9749 9767 9769 9781 9787 9791
9817 9829 9833 9839 9851 9857 9859 9871
9901 9907 9923 9929 9931 9941 9949 9967
Total of 1229 prime numbers between 1 and 10000.

23
67
109
167
227
277
347
401
461

29
71
113
173
229
281
349
409
463

9803
9883
9973

9811
9887

6.31 (Reverse Digits) Write a function that takes an integer value and returns the number with its
digits reversed. For example, given the number 7631, the function should return 1367.
ANS:

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

// Exercise 6.31 Solution: Ex06_31.cpp


// Reverse the digits of a number.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int reverseDigits( int ); // function prototype

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

Exercises
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

35

int main()
{
int number; // input number
cout << "Enter a number between 1 and 9999: ";
cin >> number;
cout << "The number with its digits reversed is: ";
// find number with digits reversed
cout << reverseDigits( number ) << endl;
return 0; // indicate successful termination
} // end main
// reverseDigits returns number obtained by reversing digits of n
int reverseDigits( int n )
{
int reverse = 0; // reversed number
int divisor = 1000; // current divisor
int multiplier = 1; // current multiplier
// loop until single-digit number
while ( n > 9 )
{
// if n >= current divisor, determine digit
if ( n >= divisor )
{
// update reversed number with current digit
reverse += n / divisor * multiplier;
n %= divisor; // update n
divisor /= 10; // update divisor
multiplier *= 10; // update multiplier
} // end if
else // else, no digit
divisor /= 10; // update divisor
} // end while
reverse += n * multiplier;
return reverse; // return reversed number
} // end function reverseDigits

Enter a number between 1 and 9999: 7631


The number with its digits reversed is: 1367

6.32 The greatest common divisor (GCD) of two integers is the largest integer that evenly divides
each of the numbers. Write a function gcd that returns the greatest common divisor of two integers.
ANS:

1
2
3
4

// Exercise 6.32 Solution: Ex06_32.cpp


// Finds greatest common divisor (GCD) of 2 inputs.
#include <iostream>
using std::cin;

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

36
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

Chapter 6 Functions and an Introduction to Recursion

using std::cout;
using std::endl;
int gcd( int, int ); // function prototype
int main()
{
int a; // first number
int b; // second number
// loop for 5 pairs of inputs
for ( int j = 1; j <= 5; j++ )
{
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The greatest common divisor of "
<< a << " and " << b << " is ";
// find greatest common divisor of a and b
cout << gcd( a, b ) << endl;
} // end for
return 0; // indicate successful termination
} // end main
// gcd finds greatest common divisor of x and y
int gcd( int x, int y )
{
int greatest = 1; // current greatest common divisor, 1 is minimum
// loop from 2 to smaller of x and y
for ( int i = 2; i <= ( ( x < y ) ? x: y ); i++ )
{
// if current i divides both x and y
if ( x % i == 0 && y % i == 0 )
greatest = i; // update greatest common divisor
} // end for
return greatest; // return greatest common divisor found
} // end function gcd

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

Exercises

37

Enter two integers: 6 8


The greatest common divisor of 6 and 8 is 2
Enter two integers: 789 4
The greatest common divisor of 789 and 4 is 1
Enter two integers: 9999 27
The greatest common divisor of 9999 and 27 is 9
Enter two integers: 73652 8
The greatest common divisor of 73652 and 8 is 4
Enter two integers: 99 11
The greatest common divisor of 99 and 11 is 11

6.33 Write a function qualityPoints that inputs a students average and returns 4 if a students
average is 90100, 3 if the average is 8089, 2 if the average is 7079, 1 if the average is 6069 and
0 if the average is lower than 60.
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

// Exercise 6.33 Solution: Ex06_33.cpp


// Determine quality points on 0 to 4 scale
// for averages in 0 to 100 range.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int qualityPoints( int ); // function prototype
int main()
{
int average; // current average
// loop for 5 inputs
for ( int loop = 1; loop <= 5; loop++ )
{
cout << "\nEnter the student's average: ";
cin >> average;
// determine and display corresponding quality points
cout << average << " on a 4 point scale is "
<< qualityPoints( average ) << endl;
} // end for
cout << endl;
return 0; // indicate successful termination
} // end main
// qualityPoints takes average in range 0 to 100 and
// returns corresponding quality points on 0 to 4 scale
int qualityPoints( int average )
{

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

38
34
35
36
37
38
39
40
41
42
43
44

Chapter 6 Functions and an Introduction to Recursion

if ( average >= 90 ) // 90 <= average <= 100


return 4;
else if ( average >= 80 ) // 80 <= average <= 89
return 3;
else if ( average >= 70 ) // 70 <= average <= 79
return 2;
else if ( average >= 60 ) // 60 <= average <= 69
return 1;
else // 0 <= average < 60
return 0;
} // end function qualityPoints

Enter the student's average: 99


99 on a 4 point scale is 4
Enter the student's average: 72
72 on a 4 point scale is 2
Enter the student's average: 88
88 on a 4 point scale is 3
Enter the student's average: 65
65 on a 4 point scale is 1
Enter the student's average: 33
33 on a 4 point scale is 0

6.34 Write a program that simulates coin tossing. For each toss of the coin, the program should
print Heads or Tails. Let the program toss the coin 100 times and count the number of times each
side of the coin appears. Print the results. The program should call a separate function flip that
takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time.]
ANS:

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

// Exercise 6.34 Solution: Ex06_34.cpp


// Simulate coin tossing.
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
int flip( void ); // function prototype
int main()
{
int headsCount = 0; // total Heads count

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

Exercises
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

39

int tailsCount = 0; // total Tails count


srand( time( 0 ) ); // seed random number generator
// simulate coin toss 100 times
for ( int loop = 1; loop <= 100; loop++ )
{
if ( flip() == 0 ) // simulate coin toss, 0 refers to tails
{
tailsCount++; // update Tails count
cout << "Tails "; // display result
} // end if
else // 1 refers to heads
{
headsCount++; // update Heads count
cout << "Heads "; // display result
} // end else
if ( loop % 10 == 0 ) // 10 tosses per line
cout << endl;
} // end for
// display totals
cout << "\nThe total number of Heads was " << headsCount
<< "\nThe total number of Tails was " << tailsCount << endl;
return 0; // indicate successful termination
} // end main
// flip uses random number to simulate coin toss
int flip( void )
{
return rand() % 2; // scale by 2 for binary result
} // end function flip

Heads
Tails
Heads
Heads
Tails
Tails
Tails
Tails
Tails
Heads

Heads
Heads
Tails
Heads
Tails
Heads
Heads
Heads
Heads
Heads

Heads
Tails
Tails
Heads
Heads
Tails
Heads
Heads
Tails
Tails

Tails
Tails
Heads
Heads
Tails
Heads
Tails
Tails
Heads
Heads

Tails
Heads
Heads
Tails
Heads
Tails
Tails
Tails
Heads
Heads

Tails
Heads
Tails
Heads
Tails
Heads
Tails
Heads
Heads
Tails

Heads
Tails
Heads
Tails
Tails
Heads
Tails
Heads
Tails
Tails

Heads
Tails
Tails
Heads
Tails
Heads
Heads
Heads
Heads
Heads

Tails
Heads
Heads
Heads
Tails
Heads
Tails
Tails
Tails
Tails

Heads
Tails
Tails
Tails
Tails
Tails
Heads
Tails
Heads
Heads

The total number of Heads was 51


The total number of Tails was 49

6.35 (Computers in Education) Computers are playing an increasing role in education. Write a
program that helps an elementary school student learn multiplication. Use rand to produce two positive one-digit integers. It should then type a question such as
How much is 6 times 7?

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

40

Chapter 6 Functions and an Introduction to Recursion

The student then types the answer. Your program checks the students answer. If it is correct, print
"Very good!", then ask another multiplication question. If the answer is wrong, print "No. Please try
again.", then let the student try the same question repeatedly until the student finally gets it right.
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
45
46
47
48
49

// Exercise 6.35 Solution: Ex06_35.cpp


// Help user practice multiplication.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void multiplication(); // function prototype
int main()
{
srand( time( 0 ) ); // seed random number generator
multiplication(); // begin multiplication practice
return 0; // indicate successful termination
} // end main
// multiplication produces pairs of random numbers and
// prompts user for product
void multiplication()
{
int x; // first factor
int y; // second factor
int response = 0; // user response for product
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel
while ( response != -1
{
x = rand() % 10; //
y = rand() % 10; //

value read from user


)
generate 1-digit random number
generate 1-digit random number

cout << "How much is " << x << " times " << y << " (-1 to End)? ";
cin >> response;
// loop until sentinel value or correct response
while ( response != -1 && response != x * y )
{
cout << "No. Please try again." << endl << "? ";
cin >> response;
} // end while

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

Exercises
50
51
52
53
54
55
56
57

41

// correct response
if ( response == x * y )
cout << "Very good!" << endl << endl;
} // end while
cout << "That's all for now. Bye." << endl;
} // end function multiplication

Enter -1 to End.
How much is 4 times 9 (-1 to End)? 36
Very good!
How much is 7 times 0 (-1 to End)? 0
Very good!
How much is 7 times 8 (-1 to End)? 55
No. Please try again.
? 56
Very good!
How much is 5 times 0 (-1 to End)? -1
That's all for now. Bye.

6.36 (Computer Assisted Instruction) The use of computers in education is referred to as computerassisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This
can be eliminated by varying the computers dialogue to hold the students attention. Modify the
program of Exercise 6.35 so the various comments are printed for each correct answer and each incorrect answer as follows:
Responses to a correct answer
Very good!
Excellent!
Nice work!
Keep up the good work!

Responses to an incorrect answer


No. Please try again.
Wrong. Try once more.
Don't give up!
No. Keep trying.

Use the random number generator to choose a number from 1 to 4 to select an appropriate
response to each answer. Use a switch statement to issue the responses.
ANS:

1
2
3
4
5
6
7

// Exercise 6.36 Solution: Ex06_36.cpp


// Help user practice multiplication.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

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

42
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
55
56
57
58
59
60
61

Chapter 6 Functions and an Introduction to Recursion

#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void multiplication(); // function prototype
void correctMessage(); // function prototype
void incorrectMessage(); // function prototype
int main()
{
srand( time( 0 ) ); // seed random number generator
multiplication(); // begin multiplication practice
return 0; // indicate successful termination
} // end main
// multiplication produces pairs of random numbers and
// prompts user for product
void multiplication()
{
int x; // first factor
int y; // second factor
int response = 0; // user response for product
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel
while ( response != -1
{
x = rand() % 10; //
y = rand() % 10; //

value read from user


)
generate 1-digit random number
generate 1-digit random number

cout << "How much is " << x << " times " << y << " (-1 to End)? ";
cin >> response;
// loop until sentinel value or correct response
while ( response != -1 && response != x * y )
{
incorrectMessage();
cin >> response;
} // end while
if ( response == x * y ) // correct response
correctMessage();
} // end while
cout << "That's all for now. Bye." << endl;
} // end function multiplication
// correctMessage randomly chooses response to correct answer
void correctMessage()

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

Exercises
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

// generate random number between 0 and 3


switch ( rand() % 4 )
{
case 0:
cout << "Very good!";
break;
case 1:
cout << "Excellent!";
break;
case 2:
cout << "Nice work!";
break;
case 3:
cout << "Keep up the good work!";
break;
} // end switch

cout << endl << endl;


} // end function correctMessage
// incorrectMessage randomly chooses response to incorrect answer
void incorrectMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "No. Please try again.";
break;
case 1:
cout << "Wrong. Try once more.";
break;
case 2:
cout << "Don't give up!";
break;
case 3:
cout << "No. Keep trying.";
break;
} // end switch
cout << endl << "? ";
} // end function incorrectMessage

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

43

44

Chapter 6 Functions and an Introduction to Recursion

Enter -1 to End.
How much is 6 times 3 (-1 to End)? 18
Very good!
How much is 1 times 5 (-1 to End)? 5
Excellent!
How much is 4 times 6 (-1 to End)? 20
No. Please try again.
? 21
No. Please try again.
? 24
Very good!
How much is 6 times 9 (-1 to End)? -1
That's all for now. Bye.

6.37 More sophisticated computer-aided instruction systems monitor the students performance
over a period of time. The decision to begin a new topic often is based on the students success with
previous topics. Modify the program of Exercise 6.36 to count the number of correct and incorrect
responses typed by the student. After the student types 10 answers, your program should calculate
the percentage of correct responses. If the percentage is lower than 75 percent, your program should
print "Please ask your instructor for extra help" and terminate.
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

// Exercise 6.37 Solution: Ex06_37.cpp


// Help user practice multiplication;
// check user's progress every 10 responses.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void
void
void
bool

multiplication(); // function prototype


correctMessage(); // function prototype
incorrectMessage(); // function prototype
needHelp( int, int ); // function prototype

int main()
{
srand( time( 0 ) ); // seed random number generator
multiplication(); // begin multiplication practice
return 0; // indicate successful termination
} // end main

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

45

// multiplication produces pairs of random numbers and


// prompts user for product
void multiplication()
{
int x; // first factor
int y; // second factor
int response = 0; // user response for product
int correct = 0; // total number of correct responses
int incorrect = 0; // total number of incorrect responses
int count = 0; // count for every 10 responses
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel
while ( response != -1
{
x = rand() % 10; //
y = rand() % 10; //

value read from user


)
generate 1-digit random number
generate 1-digit random number

cout << "How much is " << x << " times " << y << " (-1 to End)? ";
cin >> response;
count++; // update total number of responses
// loop until sentinel value or correct response
while ( response != -1 && response != x * y )
{
incorrect++; // update total number of incorrect responses
if ( !( count % 10 ) ) // if 10 responses, check progress
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
incorrectMessage();
cin >> response;
count++; // update total number of responses
} // end while
if ( response == x * y ) // correct response
{
correct++; // update total number of correct responses
if ( !( count % 10 ) ) // if 10 responses, check progress
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count

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

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

Chapter 6 Functions and an Introduction to Recursion

} // end if
correctMessage();
} // end if
} // end while
cout << "That's all for now. Bye." << endl;
} // end function multiplication
// correctMessage randomly chooses response to correct answer
void correctMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "Very good!";
break;
case 1:
cout << "Excellent!";
break;
case 2:
cout << "Nice work!";
break;
case 3:
cout << "Keep up the good work!";
break;
} // end switch
cout << endl << endl;
} // end function correctMessage
// incorrectMessage randomly chooses response to incorrect answer
void incorrectMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "No. Please try again.";
break;
case 1:
cout << "Wrong. Try once more.";
break;
case 2:
cout << "Don't give up!";
break;
case 3:
cout << "No. Keep trying.";
break;
} // end switch
cout << endl << "? ";
} // end function incorrectMessage

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

Exercises
136
137
138
139
140
141
142
143
144
145
146
147
148

47

// needHelp returns true if < 75% right


bool needHelp( int right, int wrong )
{
// if < 75% right
if ( static_cast< double > ( right ) / ( right + wrong ) < .75 )
{
cout << "Please ask your instructor for extra help." << endl;
return true;
} // end if
else // otherwise, return false
return false;
} // end function needHelp

Enter -1 to End.
How much is 0 times 9 (-1 to End)? 0
Keep up the good work!
How much is 8 times 7 (-1 to End)? 55
No. Please try again.
? 56
Nice work!
...
How much is 9 times 4 (-1 to End)? 45
Please ask your instructor for extra help.

6.38 (Guess the Number Game) Write a program that plays the game of guess the number as
follows: Your program chooses the number to be guessed by selecting an integer at random in the
range 1 to 1000. The program then displays the following:
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.

The player then types a first guess. The program responds with one of the following:
1. Excellent! You guessed the number!
Would you like to play again (y or n)?
2. Too low. Try again.
3. Too high. Try again.

If the players guess is incorrect, your program should loop until the player finally gets the number
right. Your program should keep telling the player Too high or Too low to help the player zero in
on the correct answer.
ANS:

1
2
3

// Exercise 6.38 Solution: Ex06_38.cpp


// Randomly generate numbers between 1 and 1000 for user to guess.
#include <iostream>

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

48
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
55
56
57

Chapter 6 Functions and an Introduction to Recursion

using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void guessGame(); // function prototype
bool isCorrect( int, int ); // function prototype
int main()
{
srand( time( 0 ) ); // seed random number generator
guessGame();
return 0; // indicate successful termination
} // end main
// guessGame generates numbers between 1 and 1000 and checks user's guess
void guessGame()
{
int answer; // randomly generated number
int guess; // user's guess
char response; // 'y' or 'n' response to continue game
// loop until user types 'n' to quit game
do
{
// generate random number between 1 and 1000
// 1 is shift, 1000 is scaling factor
answer = 1 + rand() % 1000;
// prompt for guess
cout << "I have a number between 1 and 1000.\n"
<< "Can you guess my number?\n"
<< "Please type your first guess." << endl << "? ";
cin >> guess;
// loop until correct number
while ( !isCorrect( guess, answer ) )
cin >> guess;
// prompt for another game
cout << "\nExcellent! You guessed the number!\n"
<< "Would you like to play again (y or n)? ";
cin >> response;
cout << endl;
} while ( response == 'y' );
} // end function guessGame

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

Exercises
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

49

// isCorrect returns true if g equals a


// if g does not equal a, displays hint
bool isCorrect( int g, int a )
{
// guess is correct
if ( g == a )
return true;
// guess is incorrect; display hint
if ( g < a )
cout << "Too low. Try again.\n? ";
else
cout << "Too high. Try again.\n? ";
return false;
} // end function isCorrect

I have a number between 1 and 1000.


Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
? 250
Too low. Try again.
? 375
Too low. Try again.
? 438
Too high. Try again.
? 405
Too high. Try again.
? 380
Too low. Try again.
? 393
Too low. Try again.
? 399
Too high. Try again.
? 396
Too low. Try again.
? 398
Too high. Try again.
? 397
Excellent! You guessed the number!
Would you like to play again (y or n)? n

6.39 Modify the program of Exercise 6.38 to count the number of guesses the player makes. If
the number is 10 or fewer, print "Either you know the secret or you got lucky!" If the player
guesses the number in 10 tries, then print "Ahah! You know the secret!" If the player makes more

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

50

Chapter 6 Functions and an Introduction to Recursion

than 10 guesses, then print "You should be able to do better!" Why should it take no more
than 10 guesses? Well, with each good guess the player should be able to eliminate half of the
numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.
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
45
46
47
48
49

// Exercise 6.39 Solution: Ex06_39.cpp


// Randomly generate numbers between 1 and 1000 for user to guess;
// analyze number of guesses before correct response.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void guessGame(); // function prototype
bool isCorrect( int, int ); // function prototype
void analyzeCount( int ); // function prototype
int main()
{
srand( time( 0 ) ); // seed random number generator
guessGame();
return 0; // indicate successful termination
} // end main
// guessGame generates numbers between 1 and 1000
// and checks user's guess
void guessGame()
{
int answer; // randomly generated number
int guess; // user's guess
int total; // number of guesses
char response; // 'y' or 'n' response to continue game
// loop until user types 'n' to quit game
do
{
// generate random number between 1 and 1000
// 1 is shift, 1000 is scaling factor
answer = 1 + rand() % 1000;
total = 0; // clear total
// prompt for guess
cout << "I have a number between 1 and 1000.\n"
<< "Can you guess my number?\n"
<< "Please type your first guess." << endl << "? ";
cin >> guess;
total++;

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

Exercises
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
89
90
91
92
93

// loop until correct number


while ( !isCorrect( guess, answer ) )
{
cin >> guess;
total++;
} // end while
cout << "\nExcellent! You guessed the number!\n";
analyzeCount( total );
// prompt for another game
cout << "Would you like to play again (y or n)? ";
cin >> response;
cout << endl;
} while ( response == 'y' );
} // end function guessGame
// isCorrect returns true if g equals a
// if g does not equal a, displays hint
bool isCorrect( int g, int a )
{
if ( g == a ) // guess is correct
return true;
// guess is incorrect; display hint
if ( g < a )
cout << "Too low. Try again.\n? ";
else
cout << "Too high. Try again.\n? ";
return false;
} // end function isCorrect
// analyzeCount determines if user knows "secret"
void analyzeCount( int count )
{
if ( count < 10 )
cout << "Either you know the secret or you got lucky!\n";
else if ( count == 10 )
cout << "Ahah! You know the secret!\n";
else
cout << "You should be able to do better!\n\n";
} // end function analyzeCount

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

51

52

Chapter 6 Functions and an Introduction to Recursion

I have a number between 1 and 1000.


Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
? 250
Too low. Try again.
? 375
Too high. Try again.
? 313
Too low. Try again.
? 344
Too low. Try again.
? 360
Too high. Try again.
? 352
Too high. Try again.
? 348
Too low. Try again.
? 350
Too low. Try again.
? 351
Excellent! You guessed the number!
Ahah! You know the secret!
Would you like to play again (y or n)? n

6.40

Write a recursive function power( base, exponent ) that, when invoked, returns
base exponent

For example, power( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal
to 1. Hint: The recursion step would use the relationship
base exponent = base base exponent - 1

and the terminating condition occurs when exponent is equal to 1, because


base1 = base

ANS:

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

// Exercise 6.40 Solution: Ex06_40.cpp


// Recursive exponentiation.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
long power( long, long ); // function prototype
int main()
{
long b; // base

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

Exercises
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

53

long e; // exponent
cout << "Enter a base and an exponent: ";
cin >> b >> e;
// calculate and display b^e
cout << b << " raised to the " << e << " is " << power( b, e ) << endl;
return 0; // indicate successful termination
} // end main
// power recursively calculates base^exponent, assume exponent >= 1
long power( long base, long exponent )
{
if ( exponent == 1 ) // base case: exponent equals 1, return base
return base;
else // recursion step
return base * power( base, exponent - 1 );
} // end function power

Enter a base and an exponent: 3 4


3 raised to the 4 is 81

6.41

(Fibonacci Series) The Fibonacci series


0, 1, 1, 2, 3, 5, 8, 13, 21,

begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two
preceding terms. (a) Write a nonrecursive function fibonacci( n ) that calculates the nth Fibonacci
number. (b) Determine the largest int Fibonacci number that can be printed on your system. Modify the program of part (a) to use double instead of int to calculate and return Fibonacci numbers,
and use this modified program to repeat part (b).
ANS:

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

// Exercise 6.41 Part A Solution: Ex06_41.cpp


// Nonrecursively calculate Fibonacci numbers.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int fibonacci( int ); // function prototype
int main()
{
// calculate the fibonacci values of 0 through 10
for ( int counter = 0; counter <= 10; counter++ )
cout << "fibonacci( " << counter << " ) = "
<< fibonacci( counter ) << endl;
// display higher fibonacci values
cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;

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

54
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

Chapter 6 Functions and an Introduction to Recursion

cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;


cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
return 0; // indicates successful termination
} // end main
// fibonacci nonrecursively calculates nth Fibonacci number
int fibonacci( int n )
{
int fib0 = 0; // after iteration, holds fib(i-1), initially fib(0) = 0
int fib1 = 1; // after iteration, holds fib(i), initially fib(1) = 1
int temp; // temporary holder for updating fib0 and fib1
if ( n == 0 ) // special case if n is 0
return 0;
// loop until nth number reached
for ( int i = 2; i <= n; i++ )
{
// note at this point:
// fib0 = fib(i-2)
// fib1 = fib(i-1)
temp = fib1; // temporarily hold fib(i-1)
// update fib1 to hold fib(i), fib(i) = fib(i-1) + fib(i-2)
fib1 = fib0 + fib1;
fib0 = temp; // update fib0 to hold fib(i-1)
// note at this point:
// fib0 = fib(i-1)
// fib1 = fib(i)
} // end for
return fib1;
} // end function fibonacci

fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(

1
2

0 ) = 0
1 ) = 1
2 ) = 1
3 ) = 2
4 ) = 3
5 ) = 5
6 ) = 8
7 ) = 13
8 ) = 21
9 ) = 34
10 ) = 55
20 ) = 6765
30 ) = 832040
35 ) = 9227465

// Exercise 6.41 Part B Solution: Ex06_41.cpp


// Nonrecursively calculate Fibonacci numbers using double values.

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

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
double fibonacci( int ); // function prototype
int main()
{
// set floating-point number format
cout << fixed << setprecision( 1 );
// calculate the fibonacci values of 0 through 10
for ( int counter = 0; counter <= 10; counter++ )
cout << "fibonacci( " << counter << " ) = "
<< fibonacci( counter ) << endl;
// display higher fibonacci values
cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;
cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;
cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
return 0; // indicates successful termination
} // end main
// fibonacci nonrecursively calculates nth Fibonacci number
double fibonacci( int n )
{
// initially fib(0) = 0, after iteration, holds fib(i-1)
double fib0 = 0;
// initially fib(1) = 1, after iteration, holds fib(i)
double fib1 = 1;
double temp; // temporary holder for updating fib0 and fib1
if ( n == 0 ) // special case if n is 0
return 0;
// loop until nth number reached
for ( int i = 2; i <= n; i++ )
{
// note at this point:
// fib0 = fib(i-2)
// fib1 = fib(i-1)
temp = fib1; // temporarily hold fib(i-1)
fib1 = fib0 + fib1; // update fib1 to hold fib(i)
fib0 = temp; // update fib0 to hold fib(i-1)
// note at this point:
// fib0 = fib(i-1)

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

55

56
57
58
59
60
61

Chapter 6 Functions and an Introduction to Recursion

// fib1 = fib(i)
} // end for
return fib1;
} // end function fibonacci

fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(
fibonacci(

0 ) = 0.0
1 ) = 1.0
2 ) = 1.0
3 ) = 2.0
4 ) = 3.0
5 ) = 5.0
6 ) = 8.0
7 ) = 13.0
8 ) = 21.0
9 ) = 34.0
10 ) = 55.0
20 ) = 6765.0
30 ) = 832040.0
35 ) = 9227465.0

6.42 (Towers of Hanoi) In this chapter, you studied functions that can be easily implemented
both recursively and iteratively. In this exercise, we present a problem whose recursive solution demonstrates the elegance of recursion, and whose iterative solution may not be as apparent.
The Towers of Hanoi is one of the most famous classic problems every budding computer scientist must grapple with. Legend has it that in a temple in the Far East, priests are attempting to
move a stack of golden disks from one diamond peg to another (Fig. 6.41). The initial stack has 64
disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are
attempting to move the stack from one peg to another under the constraints that exactly one disk is
moved at a time and at no time may a larger disk be placed above a smaller disk. Three pegs are
provided, one being used for temporarily holding disks. Supposedly, the world will end when the
priests complete their task, so there is little incentive for us to facilitate their efforts.
Let us assume that the priests are attempting to move the disks from peg 1 to peg 3. We wish
to develop an algorithm that prints the precise sequence of peg-to-peg disk transfers.
If we were to approach this problem with conventional methods, we would rapidly nd ourselves hopelessly knotted up in managing the disks. Instead, attacking this problem with recursion
in mind allows the steps to be simple. Moving n disks can be viewed in terms of moving only n
1 disks (hence, the recursion), as follows:
a) Move n 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
b) Move the last disk (the largest) from peg 1 to peg 3.
c) Move the n 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area.

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

Exercises
peg 1

peg 2

57

peg 3

Fig. 6.41 | Towers of Hanoi for the case with four disks.
The process ends when the last task involves moving n = 1 disk (i.e., the base case). This task
is accomplished by simply moving the disk, without the need for a temporary holding area.
Write a program to solve the Towers of Hanoi problem. Use a recursive function with four
parameters:
a) The number of disks to be moved
b) The peg on which these disks are initially threaded
c) The peg to which this stack of disks is to be moved
d) The peg to be used as a temporary holding area
Your program should print the precise instructions it will take to move the disks from the
starting peg to the destination peg. For example, to move a stack of three disks from peg 1 to peg 3,
your program should print the following series of moves:
1 3 (This means move one disk from peg 1 to peg 3.)
1 2
3 2
1 3
2 1
2 3
1 3
ANS:

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

// Exercise 6.42 Solution: Ex06_42.cpp


// Towers of Hanoi problem.
#include <iostream>
using std::cout;
using std::cin;
void towers( int, int, int, int ); // function prototype
int main()
{
int nDisks; // number of disks
cout << "Enter the starting number of disks: ";

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

58
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

Chapter 6 Functions and an Introduction to Recursion

cin >> nDisks;


// print instructions for moving disks from
// peg 1 to peg 3 using peg 2 for temporary storage
towers( nDisks, 1, 3, 2 );
return 0; // indicate successful termination
} // end main
// towers recursively prints instructions for moving disks from
// start peg to end peg using temp peg for temporary storage
void towers( int disks, int start, int end, int temp )
{
if ( disks == 1 ) // base case
cout << start << " --> " << end << '\n';
else // recursion step
{
// move disks - 1 disks from start to temp
towers( disks - 1, start, temp, end );
// move last disk from start to end
cout << start << " --> " << end << '\n';
// move disks - 1 disks from temp to end
towers( disks - 1, temp, end, start );
} // end else
} // end function towers

Enter
1 -->
1 -->
2 -->
1 -->
3 -->
3 -->
1 -->
1 -->
2 -->
2 -->
3 -->
2 -->
1 -->
1 -->
2 -->

the starting number of disks: 4


2
3
3
2
1
2
2
3
3
1
1
3
2
3
3

6.43 Any program that can be implemented recursively can be implemented iteratively, although
sometimes with more difficulty and less clarity. Try writing an iterative version of the Towers of
Hanoi. If you succeed, compare your iterative version with the recursive version developed in
Exercise 6.42. Investigate issues of performance, clarity and your ability to demonstrate the correctness of the programs.
6.44 (Visualizing Recursion) It is interesting to watch recursion in action. Modify the factorial
function of Fig. 6.29 to print its local variable and recursive call parameter. For each recursive call,
display the outputs on a separate line and add a level of indentation. Do your utmost to make the

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

Exercises

59

outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities
to the many other recursion examples and exercises throughout the text.
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

// Exercise 6.44 Solution: Ex06_44.cpp


// Visualizing recursion with factorial function.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
unsigned long factorial( unsigned long ); // function prototype
int main()
{
// Loop 10 times. During each iteration, calculate
// factorial( i ) and display result.
for ( int i = 0; i <= 10; i++ )
cout << setw( 2 ) << i << "! = " << factorial( i ) << endl;
return 0; // indicates successful termination
} // end main
// recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
if ( number <= 1 ) // base case
{
cout << "
Reached base case of 1" << endl;
return 1;
} // end if
else // recursion step
{
// add outputs and indentation to help visualize recursion
cout << setw( number * 3 ) << ""
<< "local variable number: " << number << endl;
cout << setw( number * 3 ) << ""
<< "recursively calling factorial( "
<< number - 1 << " )" << endl << endl;
return ( number * factorial( number - 1 ) );
} // end else
} // end function factorial

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

60

Chapter 6 Functions and an Introduction to Recursion

Calculating factorial ( 0 )
Reached base case of 1
0! = 1
Calculating factorial ( 1 )
Reached base case of 1
1! = 1
Calculating factorial ( 2 )
local variable number: 2
recursively calling factorial( 1 )
Reached base case of 1
2! = 2
...
Calculating factorial ( 10 )

local variable number: 10


recursively calling factorial( 9 )

local variable number: 9


recursively calling factorial( 8 )
local variable number: 8
recursively calling factorial( 7 )
local variable number: 7
recursively calling factorial( 6 )
local variable number: 6
recursively calling factorial( 5 )
local variable number: 5
recursively calling factorial( 4 )
local variable number: 4
recursively calling factorial( 3 )
local variable number: 3
recursively calling factorial( 2 )
local variable number: 2
recursively calling factorial( 1 )
Reached base case of 1
10! = 3628800

6.45 (Recursive Greatest Common Divisor) The greatest common divisor of integers x and y is the
largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y, defined recursively as follows: If y is equal to 0, then gcd( x, y ) is

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

Exercises
x;

otherwise, gcd( x, y ) is gcd( y,


algorithm, x must be larger than y.]

x % y ),

61

where % is the modulus operator. [Note: For this

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

// Exercise 6.45 Solution: Ex06_45.cpp


// Recursive greatest common divisor.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
unsigned gcd( unsigned int, unsigned int ); // function prototype
int main()
{
unsigned x; // first integer
unsigned y; // second integer
cout << "Enter two integers: ";
cin >> x >> y;
cout << "Greatest common divisor of " << x << " and "
<< y << " is " << gcd( x, y ) << endl;
return 0; // indicate successful termination
} // end main
// gcd recursively finds greatest common divisor of a and b
unsigned gcd( unsigned a, unsigned b )
{
if ( b == 0 ) // base case
return a;
else // recursion step
return gcd( b, a % b );
} // end function gcd

Enter two integers: 32727 9


Greatest common divisor of 32727 and 9 is 3

6.46 Can main be called recursively on your system? Write a program containing a function main.
Include static local variable count and initialize it to 1. Postincrement and print the value of count
each time main is called. Compile your program. What happens?
ANS:

1
2
3
4
5
6
7
8

// Exercise 6.46 Solution: Ex06_46.cpp


// Recursively calling main.
#include <iostream>
using std::cout;
using std::endl;
int main()
{

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

62
9
10
11
12
13
14
15

Chapter 6 Functions and an Introduction to Recursion

// static local variable count, initialized to 1


static int count = 1;
cout << count++ << endl; // postincrement and print value of count
main(); // call main recursively
return 0; // indicate successful termination
} // end main

1
2
3
...
12298
12299
12300
12301
12302
12303
12304
...

6.47 Exercises 6.356.37 developed a computer-assisted instruction program to teach an elementary school student multiplication. This exercise suggests enhancements to that program.
a) Modify the program to allow the user to enter a grade-level capability. A grade level of
1 means to use only single-digit numbers in the problems, a grade level of 2 means to
use numbers as large as two digits, etc.
b) Modify the program to allow the user to pick the type of arithmetic problems he or she
wishes to study. An option of 1 means addition problems only, 2 means subtraction
problems only, 3 means multiplication problems only, 4 means division problems only
and 5 means a random mix of problems of all these types.
ANS:

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

// Exercise 6.47 Part A Solution: Ex06_47.cpp


// Help user practice multiplication according to grade level;
// check user's progress every 10 responses.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
using std::pow;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void multiplication( int ); // function prototype

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

Exercises
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
65
66
67
68
69
70
71
72
73

63

int randValue( int ); // function prototype


void correctMessage(); // function prototype
void incorrectMessage(); // function prototype
bool needHelp( int, int ); // function prototype
int main()
{
int gradeLevel; // grade-level capability
cout << "Enter the grade-level: ";
cin >> gradeLevel;
srand( time( 0 ) ); // seed random number generator
multiplication( gradeLevel ); // begin multiplication practice
return 0; // indicate successful termination
} // end main
// multiplication produces pairs of random numbers and
// prompts user for product; level determines size of numbers
void multiplication( int level )
{
int x; // first factor
int y; // second factor
int response = 0; // user response for product
int correct = 0; // total number of correct responses
int incorrect = 0; // total number of incorrect responses
int count = 0; // count for every 10 responses
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel value read from user
while ( response != -1 )
{
// generate random numbers depending on level
x = randValue( level );
y = randValue( level );
cout << "How much is " << x << " times " << y << " (-1 to End)? ";
cin >> response;
count++; // update total number of responses
// loop until sentinel value or correct response
while ( response != -1 && response != x * y )
{
incorrect++; // update total number of incorrect responses
// if 10 responses, check progress
if ( !( count % 10 ) )
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;

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

64
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

Chapter 6 Functions and an Introduction to Recursion

// clear count
count = 0;
} // end if
incorrectMessage();
cin >> response;
count++; // update total number of responses
} // end while
// correct response
if ( response == x * y )
{
correct++; // update total number of correct responses
if ( !( count % 10 ) ) // if 10 responses, check progress
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
correctMessage();
} // end if
} // end while
cout << "That's all for now. Bye." << endl;
} // end function multiplication
// randValue returns random number whose size is determined by level (1-5)
int randValue( int level )
{
// generate random number according to level
return rand() % ( static_cast< int > ( pow( 10.0, level ) ) );
} // end function randValue
// correctMessage randomly chooses response to correct answer
void correctMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "Very good!";
break;
case 1:
cout << "Excellent!";
break;
case 2:
cout << "Nice work!";
break;
case 3:
cout << "Keep up the good work!";

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

Exercises
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
163
164
165
166
167
168

break;
} // end switch
cout << endl << endl;
} // end function correctMessage
// incorrectMessage randomly chooses response to incorrect answer
void incorrectMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "No. Please try again.";
break;
case 1:
cout << "Wrong. Try once more.";
break;
case 2:
cout << "Don't give up!";
break;
case 3:
cout << "No. Keep trying.";
break;
} // end switch
cout << endl << "? ";
} // end function incorrectMessage
// needHelp returns true if < 75% right
bool needHelp( int right, int wrong )
{
// if < 75% right
if ( static_cast< double > ( right ) / ( right + wrong ) < .75 )
{
cout << "Please ask your instructor for extra help." << endl;
return true;
} // end if
else // otherwise, return false
return false;
} // end function needHelp

Enter the grade-level (1 to 3): 3


How much is 643 times 462? 297066
Very good!
How much is 763 times 731? 537753
Don't give up!
? 557753
Keep up the good work!
How much is 382 times 120?
...

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

65

66
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

Chapter 6 Functions and an Introduction to Recursion

// Exercise 6.47 Part B Solution: Ex06_48.cpp


// Help user practice arithmetic according to grade level;
// user can choose between addition, subtraction,
// multiplication, division or random mix.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
using std::pow;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void arithmetic( int, int ); // function prototype
int randValue( int ); // function prototype
int generateProblem( int, int ); // function prototype
void correctMessage(); // function prototype
void incorrectMessage(); // function prototype
bool needHelp( int, int ); // function prototype
int main()
{
int choice; // type of problem
int gradeLevel; // grade-level capability
do
{

cout << "Choose


<< "\nEnter:
<< "\nEnter:
<< "\nEnter:
cin >> choice;
} while ( choice <

type of problem to study."


1 for addition, 2 for subtraction"
3 for multiplication, 4 for division"
5 for a combination of 1 through 4\n? ";
1 || choice > 5 );

cout << "\nEnter the grade-level: ";


cin >> gradeLevel;
srand( time( 0 ) ); // seed random number generator
arithmetic( choice, gradeLevel ); // begin arithmetic practice
return 0; // indicate successful termination
} // end main
// arithmetic produces pairs of random numbers and prompts user for answer
// to arithmetic problem; level determines size of numbers
void arithmetic( int type, int level )
{
int response = 0; // user response for product
int correct = 0; // total number of correct responses

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

Exercises
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

int incorrect = 0; // total number of incorrect responses


int count = 0; // count for every 10 responses
int answer; // correct answer
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel value read from user
while ( response != -1 )
{
// generate problem
answer = generateProblem( type, level );
cin >> response;
count++;
// loop until sentinel value or correct response
while ( response != -1 && response != answer )
{
incorrect++; // update total number of incorrect responses
// if 10 responses, check progress
if ( !( count % 10 ) )
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
incorrectMessage();
cin >> response;
count++; // update total number of responses
} // end while
// correct response
if ( response == answer )
{
correct++; // update total number of correct responses
// if 10 responses, check progress
if ( !( count % 10 ) )
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
correctMessage();
} // end if
} // end while

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

67

68
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

Chapter 6 Functions and an Introduction to Recursion

cout << "That's all for now. Bye." << endl;


} // end function arithmetic
// randValue returns random number whose size
// is determined by level (1-5)
int randValue( int level )
{
// generate random number according to level
return rand() % ( static_cast< int > ( pow( 10.0, level ) ) );
} // end function randValue
// generateProblem creates arithmetic problem
// option chooses type of problem:
// option 1 is addition, option 2 is subtraction,
// option 3 is multiplication, option 4 is division,
// option 5 is random mix;
// returns answer to problem
int generateProblem( int option, int level )
{
int x; // first operand
int y; // second operand
// generate random numbers depending on level
x = randValue( level );
y = randValue( level );
if ( option == 5 ) // if option 5, randomly select type
option = 1 + rand() % 4;
// generate problem depending on option
switch ( option )
{
case 1: // option 1: arithmetic
cout << "How much is " << x << " + " <<
return x + y;
case 2: // option 2: subtraction
if ( x > y ) // for positive answer
{
cout << "How much is " << x << " - "
return x - y;
} // end for
else
{
cout << "How much is " << y << " - "
return y - x;
} // end else
case 3: // option 3: multiplication
cout << "How much is " << x << " * " <<
return x * y;
case 4: // option 4: division
while ( y == 0 ) // eliminate divide by
y = randValue( level );

y << "? ";

<< y << "? ";

<< x << "? ";

y << "? ";


zero error

x *= y; // create "nice" division

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

Exercises
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

cout << "How much is " << x << " / " << y << "? ";
return x / y;
default: // default to addition
cout << "How much is " << x << " + " << y << "? ";
return x + y;
} // end switch
} // end function generateProblem
// correctMessage randomly chooses response to correct answer
void correctMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "Very good!";
break;
case 1:
cout << "Excellent!";
break;
case 2:
cout << "Nice work!";
break;
case 3:
cout << "Keep up the good work!";
break;
} // end switch
cout << endl << endl;
} // end function correctMessage
// incorrectMessage randomly chooses response to incorrect answer
void incorrectMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "No. Please try again.";
break;
case 1:
cout << "Wrong. Try once more.";
break;
case 2:
cout << "Don't give up!";
break;
case 3:
cout << "No. Keep trying.";
break;
} // end switch
cout << endl << "? ";
} // end function incorrectMessage

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

69

70
217
218
219
220
221
222
223
224
225
226
227
228

Chapter 6 Functions and an Introduction to Recursion

// needHelp returns true if < 75% right


bool needHelp( int right, int wrong )
{
// if < 75% right
if ( static_cast< double > ( right ) / ( right + wrong ) < .75 )
{
cout << "Please ask your instructor for extra help." << endl;
return true;
} // end if
else // otherwise, return false
return false;
} // end function needHelp

Choose
Enter:
Enter:
Enter:
? 5

type of problem to study.


1 for addition, 2 for subtraction
3 for multiplication, 4 for division
5 for a combination of 1 through 4

Enter the grade-level: 1


Enter -1 to End.
How much is 8 / 4? 2
Nice work!
How much is 4 - 3? 1
Excellent!
How much is 6 - 1? 5
Excellent!
How much is 0 / 1? 0
Very good!
How much is 3 - 2? 1
Excellent!
...

6.48 Write function distance that calculates the distance between two points (x1, y1) and (x2,
y2). All numbers and return values should be of type double.
ANS:

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

// Exercise 6.48 Solution: Ex06_48.cpp


// Calculate distance between 2 points.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include <cmath>

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

Exercises
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

71

using std::pow;
using std::sqrt;
double distance( double, double, double, double ); // function prototype
int main()
{
double x1;
double y1;
double x2;
double y2;

//
//
//
//

x
y
x
y

coordinate
coordinate
coordinate
coordinate

of
of
of
of

first point
first point
second point
second point

// prompt for first point coordinates


cout << "Enter the first point: ";
cin >> x1 >> y1;
// prompt for second point coordinates
cout << "Enter the second point: ";
cin >> x2 >> y2;
// calculate and display distance
cout << fixed << "Distance between (" << setprecision( 1 ) << x1
<< ", " << y1 << ") and (" << x2 << ", " << y2 << ") is "
<< distance( x1, y1, x2, y2 ) << endl;
return 0; // indicate successful termination
} // end main
// distance calculates distance between 2 points
// given by (a1, b1) and (a2, b2)
double distance( double a1, double b1, double a2, double b2 )
{
return sqrt( pow( a1 - a2, 2 ) + pow( b1 - b2, 2 ) );
} // end function distance

Enter the first point: 8 9


Enter the second point: 0 1
Distance between (8.0, 9.0) and (0.0, 1.0) is 11.3

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

72

Chapter 6 Functions and an Introduction to Recursion

6.49

What is wrong with the following program?

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

// Exercise 6.49: ex06_49.cpp


// What is wrong with this program?
#include <iostream>
using std::cin;
using std::cout;
int main()
{
int c;
if ( ( c = cin.get() ) != EOF )
{
main();
cout << c;
} // end if
return 0; // indicates successful termination
} // end main
ANS: Standard C++ does not allow recursive calls of main, however, on nonstandard com-

pilers, this program would print the characters input in reverse order.

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

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

73

What does the following program do?

// Exercise 6.50: ex06_50.cpp


// What does this program do?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int mystery( int, int ); // function prototype
int main()
{
int x, y;
cout << "Enter two integers: ";
cin >> x >> y;
cout << "The result is " << mystery( x, y ) << endl;
return 0; // indicates successful termination
} // end main
// Parameter b must be a positive integer to prevent infinite recursion
int mystery( int a, int b )
{
if ( b == 1 ) // base case
return a;
else // recursion step
return a + mystery( a, b - 1 );
} // end function mystery
ANS: This program multiplies two integers recursively.

Enter two integers: 8 2


The result is 16

6.51 After you determine what the program of Exercise 6.50 does, modify the program to function properly after removing the restriction that the second argument be nonnegative.
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 6.51 Solution: Ex06_51.cpp


// Multiply integers (positive or negative) using recursion.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int mystery( int, int ); // function prototype
int main()

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

74
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

Chapter 6 Functions and an Introduction to Recursion

int x; // first integer


int y; // second integer
cout << "Enter two integers: ";
cin >> x >> y;
cout << "The result is " << mystery( x, y ) << endl;

return 0; // indicate successful termination


} // end main
// mystery multiplies a * b using recursion
int mystery( int a, int b )
{
if ( b < 0 ) // if b is negative
{
// multiply both a and b by -1, so b is positive
// note this multiplies answer by (-1)*(-1) = 1
a *= -1;
b *= -1;
} // end if
if ( b == 1 ) // base case
return a;
else // recursion step
return a + mystery( a, b - 1 );
} // end function mystery

Enter two integers: 8 -8


The result is -64

6.52 Write a program that tests as many of the math library functions in Fig. 6.2 as you can. Exercise each of these functions by having your program print out tables of return values for a diversity
of argument values.
ANS:

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

// Exercise 6.52 Solution: Ex06_52.cpp


// Test math library functions on range of values.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setw;
using std::setprecision;
#include <cmath>
using std::sqrt;
using std::exp;
using std::log;

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

using
using
using
using
using
using
using
using

75

std::log10;
std::pow;
std::fabs;
std::ceil;
std::floor;
std::sin;
std::cos;
std::tan;

void testPositiveRange(); // function prototype


void testNegativePositiveRange(); // function prototype
void testTrig(); // function prototype
int main()
{
// set floating-point number format
cout << fixed << setprecision( 2 );
// display table testing sqrt, exp, log, log10 and pow
testPositiveRange();
cout << "\n\n\n";
// display table testing fabs, ceil and floor
testNegativePositiveRange();
cout << "\n\n\n";
testTrig(); // display table testing sin, cos and tan
cout << endl;
return 0; // indicate successful termination
} // end main
// testPositiveRange tests math library functions
// sqrt, exp, log, log10 and pow on range of positive numbers
void testPositiveRange()
{
// table header for first column
cout << "function";
for ( int a = 1; a < 6; a++ ) // table headers for value columns
cout << setw( 12 ) << a << ' ';
// row data for square root function
cout << "\n\nsqrt() ";
for ( int b = 1; b < 6; b++ ) // display sqrt for range of values
cout << setw( 12 ) << sqrt( static_cast< double > ( b ) ) << ' ';
cout << "\nexp()

"; // row data for exponential function

for ( int c = 1; c < 6; c++ ) // display exp for range of values


cout << setw( 12 ) << exp( static_cast< double > ( c ) ) << ' ';
cout << "\nlog()

"; // row data for natural log function

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

76
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

Chapter 6 Functions and an Introduction to Recursion

// display natural log for range of values


for ( int d = 1; d < 6; d++ )
cout << setw( 12 ) << log( static_cast< double > ( d ) ) << ' ';
cout << "\nlog10() "; // row data for log base 10 function
// display log base 10 for range of values
for ( int e = 1; e < 6; e++ )
cout << setw( 12 ) << log10( static_cast< double > ( e ) ) << ' ';
// row data for pow function, test with 2 as base
cout << "\npow(2,x)";
for ( int f = 1; f < 6; f++ ) // display pow for range of values
cout << setw( 12 ) << pow( 2.0, f ) << ' ';
} // end function testPositiveRange
// testNegativePositiveRange tests math library functions
// fabs, ceil and floor on range of negative and positive numbers
void testNegativePositiveRange()
{
cout << "function"; // table header for first column
// table headers for value columns
for ( double g = -1.5; g < 3.0; g += 1.1 )
cout << setw( 12 ) << g << ' ';
cout << "\n\nfabs()

"; // row data for absolute value function

// display fabs for range of values


for ( double h = -1.5; h < 3.0; h += 1.1 )
cout << setw( 12 ) << fabs( h ) << ' ';
cout << "\nceil()

"; // row data for ceiling function

// display ceil for range of values


for ( double i = -1.5; i < 3.0; i += 1.1 )
cout << setw( 12 ) << ceil( i ) << ' ';
cout << "\nfloor() "; // row data for floor function
// display floor for range of values
for ( double j = -1.5; j < 3.0; j += 1.1 )
cout << setw( 12 ) << floor( j ) << ' ';
} // end function testNegativePositiveRange
// testTrig tests math library functions
// sin, cos and tan on range of radian numbers
void testTrig()
{
double pi = 3.14159; // approximate value for pi
cout << "function"; // table header for first column
// table headers for value columns

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

Exercises
124
for ( double k = ( -pi / 2.0 ); k < ( 2 * pi ); k += (
125
cout << setw( 12 ) << k << ' ';
126
127
cout << "\n\nsin()
"; // row data for sine function
128
129
// display sin for range of values
130
for ( double l = ( -pi / 2.0 ); l < ( 2 * pi ); l += (
131
cout << setw( 12 ) << sin( l ) << ' ';
132
133
cout << "\ncos()
"; // row data for cosine function
134
135
// display cos for range of values
136
for ( double m = ( -pi / 2.0 ); m < ( 2 * pi ); m += (
137
cout << setw( 12 ) << cos( m ) << ' ';
138
139
cout << "\ntan()
"; // row data for tangent function
140
141
// display tan for range of values
142
for ( double n = ( -pi / 2.0 ); n < ( 2 * pi ); n += (
143
cout << setw( 12 ) << tan( n ) << ' ';
144 } // end function testTrig

77

pi / 2.0 ) )

pi / 2.0 ) )

pi / 2.0 ) )

pi / 2.0 ) )

function

sqrt()
exp()
log()
log10()
pow(2,x)

1.00
2.72
0.00
0.00
2.00

1.41
7.39
0.69
0.30
4.00

1.73
20.09
1.10
0.48
8.00

2.00
54.60
1.39
0.60
16.00

2.24
148.41
1.61
0.70
32.00

function

-1.50

-0.40

0.70

1.80

2.90

fabs()
ceil()
floor()

1.50
-1.00
-2.00

0.40
0.00
-1.00

0.70
1.00
0.00

1.80
2.00
1.00

2.90
3.00
2.00

function

-1.57

0.00

1.57

3.14

4.71

-1.00
0.00
-753696.00

0.00
1.00
0.00

1.00
0.00
753696.00

0.00
-1.00
-0.00

-1.00
-0.00
251232.00

sin()
cos()
tan()

6.53

Find the error in each of the following program segments and explain how to correct it:
a) float cube( float ); // function prototype
double cube( float number ) // function definition
{
return number * number * number;
}

ANS: Error: The function definition defaults to a return type of int.

Correction: Specify a return type of float for the definition.

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

78

Chapter 6 Functions and an Introduction to Recursion


b)

register auto int x = 7;

c)

int randomNumber = srand();

d)

float y = 123.45678;

ANS: Error: Only one storage class specifier can be used.

Correction: Remove either register or auto.

ANS: Error: Function srand takes an unsigned argument and does not return a value.

Correction: Use rand instead of srand.

int x;
x = y;
cout << static_cast< float >( x ) << endl;

ANS: Error: The assignment of y to x truncates decimal places.

e)

Correction: Declare x as type float instead of int.

double square( double number )


{
double number;
return number * number;
}

ANS: Error: Variable number is declared twice.

f)

Correction: Remove the declaration of variable number within the {}.

int sum( int n )


{
if ( n == 0 )
return 0;
else
return n + sum( n );
}

ANS: Error: Infinite recursion.

Correction: Change operator + to operator -.

6.54 Modify the craps program of Fig. 6.11 to allow wagering. Package as a function the portion
of the program that runs one game of craps. Initialize variable bankBalance to 1000 dollars. Prompt
the player to enter a wager. Use a while loop to check that wager is less than or equal to bankBalance
and, if not, prompt the user to reenter wager until a valid wager is entered. After a correct wager is
entered, run one game of craps. If the player wins, increase bankBalance by wager and print the new
bankBalance. If the player loses, decrease bankBalance by wager, print the new bankBalance, check
on whether bankBalance has become zero and, if so, print the message "Sorry. You busted!" As
the game progresses, print various messages to create some chatter such as "Oh, you're going for
broke, huh?", "Aw cmon, take a chance!" or "You're up big. Now's the time to cash in your
chips!".
ANS:

1
2
3
4
5
6
7
8
9

// Exercise 6.54 Solution: Ex06_54.cpp


// Craps game simulation with wagering.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib> // contains prototypes for functions srand and rand
using std::rand;

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

Exercises
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
55
56
57
58
59
60
61
62
63

using std::srand;
#include <ctime> // contains prototype for function time
using std::time;
// enumeration constants represent game status
enum Status { WON, LOST, CONTINUE };
int rollDice( void ); // function prototype
Status craps( void ); // function prototype
void chatter( void ); // function prototype
int main()
{
Status result; // result of current game
int wager = 0; // wager for current game
int bankBalance = 1000; // current bank balance
char playAgain; // whether user wants to play another game
// randomize random number generator using current time
srand( time( 0 ) );
// loop until user enters sentinel value
do
{
// display current balance and prompt for wager
cout << "You have $" << bankBalance
<< " in the bank.\nPlace your wager: ";
cin >> wager;
// loop until valid wager
while ( wager <= 0 || wager > bankBalance )
{
cout << "Please bet a valid amount.\n";
cin >> wager;
} // end while
result = craps(); // play game of craps
if ( result == LOST ) // if player lost current game
{
bankBalance -= wager; // decrease balance by wager
// display new balance
cout << "Your new bank balance is $" << bankBalance << "\n";
if ( bankBalance == 0 ) // balance is 0
{
// display message
cout << "Sorry. You Busted! Thank You For Playing.\n";
break; // break out of while loop
} // end if
} // end if
else // else, player won current game

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

79

80
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
109
110
111
112
113
114
115
116
117

Chapter 6 Functions and an Introduction to Recursion

bankBalance += wager; // increase balance by wager

// display new balance


cout << "Your new bank balance is $" << bankBalance << "\n";
} // end else
// prompt for next game
cout << "Would you like to try your luck again (y/n)? ";
cin >> playAgain;
} while ( playAgain == 'y' || playAgain == 'Y' );
cout << endl;
return 0; // indicate successful termination
} // end main
// roll dice, calculate sum and display results
int rollDice( void )
{
int die1; // first die value
int die2; // second die value
int workSum; // sum of dice
die1 = 1 + rand() % 6; // pick random die1 value
die2 = 1 + rand() % 6; // pick random die2 value
workSum = die1 + die2; // sum die1 and die2
// display results of this roll
cout << "Player rolled " << die1 << " + " << die2
<< " = " << workSum << endl;
return workSum; // return sum of dice
} // end function rollDice
// craps plays one game of craps, returns result of game
Status craps( void )
{
int sum; // current roll of dice
int myPoint; // point value
Status gameStatus; // can contain CONTINUE, WON or LOST
sum = rollDice(); // first roll of dice
// determine game status and point based on sum of dice
switch ( sum )
{
case 7: // win on first roll
case 11:
gameStatus = WON;
break;
case 2: // lose on first roll
case 3:
case 12:
gameStatus = LOST;

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

Exercises
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
163
164
165
166
167
168
169
170
171

81

break;
default: // remember point
gameStatus = CONTINUE;
myPoint = sum;
cout << "Point is " << myPoint << '\n';
break;
} // end switch
// while game not complete ...
while ( gameStatus == CONTINUE )
{
chatter(); // create "chatter"
sum = rollDice(); // roll dice again
// determine game status
if ( sum == myPoint )
gameStatus = WON; // win by making point
else
{
if ( sum == 7 ) // lose by rolling 7
gameStatus = LOST;
} // end else
} // end while
// display won or lost message and return status
if ( gameStatus == WON )
{
cout << "Player wins" << endl;
return WON;
} // end if
else
{
cout << "Player loses" << endl;
return LOST;
} // end else
} // end function craps
// chatter displays messages at random to create "chatter"
void chatter()
{
// choose message at random
switch ( rand() % 9 )
{
case 0:
cout << "Oh, you're going for broke, huh?";
break;
case 1:
cout << "Aw cmon, take a chance!";
break;
case 2:
cout << "Hey, I think this guy is going to break the bank!!";
break;
case 3:
cout << "You're up big. Now's the time to cash in your chips!";

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

82

Chapter 6 Functions and an Introduction to Recursion

172
break;
173
case 4:
174
cout << "Way too lucky! Those dice have to be loaded!";
175
break;
176
case 5:
177
cout << "Bet it all! Bet it all!";
178
break;
179
case 6:
180
cout << "Can I borrow a chip?";
181
break;
182
case 7:
183
cout << "Let's try our luck at another table.";
184
break;
185
case 8:
186
cout << "You're a cheat! It is just a matter of time"
187
<< "\nbefore I catch you!!!";
188
break;
189
} // end switch
190
191
cout << endl;
192 } // end function chatter
You have $1000 in the bank.
Place your wager: 1000
Player rolled 3 + 4 = 7
Player wins
Your new bank balance is $2000
Would you like to try your luck again (y/n)? y
You have $2000 in the bank.
Place your wager: 2000
Player rolled 2 + 6 = 8
Point is 8
Can I borrow a chip?
Player rolled 6 + 5 = 11
You're a cheat! It is just a matter of time
before I catch you!!!
Player rolled 6 + 1 = 7
Player loses
Your new bank balance is $0
Sorry. You Busted! Thank You For Playing.

6.55 Write a C++ program that prompts the user for the radius of a circle then calls inline function circleArea to calculate the area of that circle.
ANS:

1
2
3
4
5
6
7

// Exercise 6.55 Solution: Ex06_55.cpp


// Use inline function to calculate circle area.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

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

Exercises
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

83

double pi = 3.14159; // global variable


// circleArea is inline function that returns area of circle
inline double circleArea( double r )
{
return pi * r * r; // return area
} // end function circleArea
int main()
{
double radius; // user entered radius
// prompt for radius
cout << "Enter the radius of the circle: ";
cin >> radius;
// calculate and display area of circle
cout << "The area of the circle is " << circleArea( radius ) << endl;
return 0; // indicate successful termination
} // end main

Enter the radius of the circle: 10


The area of the circle is 314.159

6.56 Write a complete C++ program with the two alternate functions specified below, of which
each simply triples the variable count defined in main. Then compare and contrast the two approaches. These two functions are
a) function tripleByValue that passes a copy of count by value, triples the copy and returns the new value and
b) function tripleByReference that passes count by reference via a reference parameter
and triples the original value of count through its alias (i.e., the reference parameter).
ANS:

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

// Exercise 6.56 Solution: Ex06_56.cpp


// Comparing call by value and call by reference.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int tripleByValue( int ); // function prototype
void tripleByReference( int & ); // function prototype
int main()
{
int count; // local variable for testing
// prompt for count value
cout << "Enter a value for count: ";
cin >> count;

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

84
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

Chapter 6 Functions and an Introduction to Recursion

// using call by value


cout << "\nValue of count before call to tripleByValue() is: "
<< count << "\nValue returned from tripleByValue() is: "
<< tripleByValue( count )
<< "\nValue of count (in main) after tripleCallByValue() is: "
<< count;
// using call by reference
cout << "\n\nValue of count before call to tripleByReference() is: "
<< count << endl;
tripleByReference( count );
cout << "Value of count (in main) after call to "
<< "tripleByReference() is: " << count << endl;
return 0; // indicate successful termination
} // end main
// tripleByValue uses call by value parameter passing to triple value
int tripleByValue( int value )
{
return value *= 3;
} // end function tripleByValue
// tripleByReference uses call by referece parameter passing
// to triple variable referenced by valueRef
void tripleByReference( int &valueRef )
{
valueRef *= 3;
} // end function tripleByReference

Enter a value for count: 8


Value of count before call to tripleByValue() is: 8
Value returned from tripleByValue() is: 24
Value of count (in main) after tripleCallByValue() is: 8
Value of count before call to tripleByReference() is: 8
Value of count (in main) after call to tripleByReference() is: 24

6.57

What is the purpose of the unary scope resolution operator?


ANS: The unary scope resolution operator is used to access a global variable. In particular,
the unary scope resolution operator is useful when a programmer needs to access a
global variable when a local variable exists with the same name.

6.58 Write a program that uses a function template called min to determine the smaller of two
arguments. Test the program using integer, character and floating-point number arguments.
ANS:

1
2
3
4

// Exercise 6.58 Solution: Ex06_58.cpp


// Finding the min using a function template.
#include <iostream>
using std::cin;

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

Exercises
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

85

using std::cout;
using std::endl;
// definition of function template min that finds the smaller of 2 values
template < class T >
T min( T value1, T value2 )
{
if ( value1 < value2 )
return value1;
else
return value2;
} // end function template min
int main()
{
// demonstrate min with int values
int int1; // first int value
int int2; // second int value
cout << "Input two integer values: ";
cin >> int1 >> int2;
// invoke int version of min
cout << "The smaller integer value is: " << min( int1, int2 );
// demonstrate min with char values
char char1; // first char value
char char2; // second char value
cout << "\n\nInput two characters: ";
cin >> char1 >> char2;
// invoke char version of min
cout << "The smaller character value is: " << min( char1, char2 );
// demonstrate min with double values
double double1; // first double value
double double2; // second double value
cout << "\n\nInput two double values: ";
cin >> double1 >> double2;
// invoke double version of min
cout << "The smaller double value is: " << min( double1, double2 )
<< endl;
return 0; // indicate successful termination
} // end main

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

Exercises

86

Input two integer values: 7 54


The smaller integer value is: 7
Input two characters: x e
The smaller character value is: e
Input two double values: 8.46 4.35
The smaller double value is: 4.35

6.59 Write a program that uses a function template called max to determine the largest of three
arguments. Test the program using integer, character and floating-point number arguments.
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

// Exercise 6.59 Solution: Ex06_59.cpp


// Finding the max using a function template.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
// definition of function template max that finds the larger of 2 values
template < class T >
T max( T value1, T value2 )
{
if ( value1 > value2 )
return value1;
else
return value2;
} // end function template max
int main()
{
// demonstrate max with int values
int int1; // first int value
int int2; // second int value
cout << "Input two integer values: ";
cin >> int1 >> int2;
// invoke int version of max
cout << "The larger integer value is: " << max( int1, int2 );
// demonstrate max with char values
char char1; // first char value
char char2; // second char value
cout << "\n\nInput two characters: ";
cin >> char1 >> char2;
// invoke char version of max
cout << "The larger character value is: " << max( char1, char2 );

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

87
40
41
42
43
44
45
46
47
48
49
50
51

Chapter 6 Functions and an Introduction to Recursion

// demonstrate max with double values


double double1; // first double value
double double2; // second double value
cout << "\n\nInput two double values: ";
cin >> double1 >> double2;
// invoke double version of max
cout << "The larger double value is: " << max( double1, double2 )
<< endl;
return 0; // indicate successful termination
} // end main

Input two integer values: 7 54


The larger integer value is: 54
Input two characters: x e
The larger character value is: x
Input two double values: 8.46 4.35
The larger double value is: 8.46

6.60 Determine whether the following program segments contain errors. For each error, explain
how it can be corrected. [Note: For a particular program segment, it is possible that no errors are
present in the segment.]
a) template < class A >
int sum( int num1, int num2, int num3 )
{
return num1 + num2 + num3;
}

ANS: Error: The function return type and parameter types are int.

b)

Correction: The function return type and parameter types should be A.

void printResults( int x, int y )


{
cout << "The sum is " << x + y << '\n';
return x + y;
}

ANS: Error: The function specifies a void return type and attempts to return a value.

c)

Two possible solutions: (1) change void to int, or (2) remove the line return

template < A >


A product( A num1, A num2, A num3 )
{
return num1 * num2 * num3;
}

ANS: Error: Keyword class is missing in the template declaration.

Correction: Insert keyword class, as in template

<class A>.

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

x + y;.

Exercises
d)

88

double cube( int );


int cube( int );

ANS: Error: The signatures are not different. Overloaded functions must have different sig-

naturesthe name and parameter list must be different. If only the returns types differ, the compiler generates an error message.
Correction: Change either the name or parameter list of one of the functions.

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