Beruflich Dokumente
Kultur Dokumente
Functions
and an
Introduction
Form ever follows function.
to Recursion
Louis Henri Sullivan
E pluribus unum.
(One composed of many.)
Virgil OBJECTIVES
O! call back yesterday, bid In this chapter you will learn:
time return.
William Shakespeare To construct programs modularly from functions.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 6 Functions and an Introduction to Recursion
Exercises
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 max-
imum 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
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:
ANS:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 3
34
35 // if first time through loop, display headers
36 if ( first )
37 {
38 cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"
39 << setw( 15 ) << "Charge\n";
40
41 first = 0; // set first to 0 to prevent from printing again
42 } // end if
43
44 // calculate current car's parking charge
45 currentCharge = calculateCharges( hour );
46 totalCharges += currentCharge; // update total charges
47
48 // display row data for current car
49 cout << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour
50 << setw( 14 ) << setprecision( 2 ) << currentCharge << "\n";
51 } // end for
52
53 // display row data for totals
54 cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )
55 << totalHours << setw( 14 ) << setprecision( 2 )
56 << totalCharges << endl;
57 return 0; // indicate successful termination
58 } // end main
59
60 // calculateCharges returns charge according to number of hours
61 double calculateCharges( double hours )
62 {
63 double charge; // calculated charge
64
65 if ( hours < 3.0 ) // $2 for up to 3 hours
66 charge = 2.0;
67 else if ( hours < 24.0 ) // $.50 for each extra hour
68 charge = 2.0 + .5 * ceil( hours - 3.0 );
69 else // maximum charge $10
70 charge = 10.0;
71
72 return charge; // return calculated charge
73 } // end function calculateCharges
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 6 Functions and an Introduction to Recursion
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5
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.18 Write a function integerPower( base, exponent ) that returns the value of
base exponent
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 6 Functions and an Introduction to Recursion
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7
28
29 cout << endl;
30 return 0; // indicate successful termination
31 } // end main
32
33 // multiple determines if b is multiple of a
34 bool multiple( int a, int b )
35 {
36 return !( b % a );
37 } // end function multiple
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 6 Functions and an Introduction to Recursion
Enter side: 4
****
****
****
****
6.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 equiv-
alents 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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 6 Functions and an Introduction to Recursion
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 num-
ber. 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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 11
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12 Chapter 6 Functions and an Introduction to Recursion
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13
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 pos-
itive one-digit integers. It should then type a question such as
How much is 6 times 7?
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 6 Functions and an Introduction to Recursion
Enter -1 to End.
How much is 4 times 9 (-1 to End)? 36
Very good!
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 15
The player then types a first guess. The program responds with one of the following:
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 6 Functions and an Introduction to Recursion
42 << "Please type your first guess." << endl << "? ";
43 cin >> guess;
44
45 // loop until correct number
46 while ( !isCorrect( guess, answer ) )
47 cin >> guess;
48
49 // prompt for another game
50 cout << "\nExcellent! You guessed the number!\n"
51 << "Would you like to play again (y or n)? ";
52 cin >> response;
53
54 cout << endl;
55 } while ( response == 'y' );
56 } // end function guessGame
57
58 // isCorrect returns true if g equals a
59 // if g does not equal a, displays hint
60 bool isCorrect( int g, int a )
61 {
62 // guess is correct
63 if ( g == a )
64 return true;
65
66 // guess is incorrect; display hint
67 if ( g < a )
68 cout << "Too low. Try again.\n? ";
69 else
70 cout << "Too high. Try again.\n? ";
71
72 return false;
73 } // end function isCorrect
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 17
? 396
Too low. Try again.
? 398
Too high. Try again.
? 397
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
ANS:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18 Chapter 6 Functions and an Introduction to Recursion
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
outputs clear, interesting and meaningful. Your goal here is to design and implement an output for-
mat 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: .
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 19
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 )
...
Calculating factorial ( 10 )
local variable number: 10
recursively calling factorial( 9 )
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
20 Chapter 6 Functions and an Introduction to Recursion
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 21
6.53 Find the error in each of the following program segments and explain how to correct it:
a) float cube( float ); // function prototype
x = y;
cout << static_cast< float >( x ) << endl;
ANS: Error: The assignment of y to x truncates decimal places.
Correction: Declare x as type float instead of int.
e) double square( double number )
{
double number;
return number * number;
}
ANS: Error: Variable number is declared twice.
Correction: Remove the declaration of variable number within the {}.
f) int sum( int n )
{
if ( n == 0 )
return 0;
else
return n + sum( n );
}
ANS: Error: Infinite recursion.
Correction: Change operator + to operator -.
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 ap-
proaches. These two functions are
a) function tripleByValue that passes a copy of count by value, triples the copy and re-
turns 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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
22 Chapter 6 Functions and an Introduction to Recursion
3 #include <iostream>
4 using std::cin;
5 using std::cout;
6 using std::endl;
7
8 int tripleByValue( int ); // function prototype
9 void tripleByReference( int & ); // function prototype
10
11 int main()
12 {
13 int count; // local variable for testing
14
15 // prompt for count value
16 cout << "Enter a value for count: ";
17 cin >> count;
18
19 // using call by value
20 cout << "\nValue of count before call to tripleByValue() is: "
21 << count << "\nValue returned from tripleByValue() is: "
22 << tripleByValue( count )
23 << "\nValue of count (in main) after tripleCallByValue() is: "
24 << count;
25
26 // using call by reference
27 cout << "\n\nValue of count before call to tripleByReference() is: "
28 << count << endl;
29
30 tripleByReference( count );
31
32 cout << "Value of count (in main) after call to "
33 << "tripleByReference() is: " << count << endl;
34 return 0; // indicate successful termination
35 } // end main
36
37 // tripleByValue uses call by value parameter passing to triple value
38 int tripleByValue( int value )
39 {
40 return value *= 3;
41 } // end function tripleByValue
42
43 // tripleByReference uses call by referece parameter passing
44 // to triple variable referenced by valueRef
45 void tripleByReference( int &valueRef )
46 {
47 valueRef *= 3;
48 } // end function tripleByReference
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 23
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
24 Chapter 6 Functions and an Introduction to Recursion
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.