Upcoming SlideShare
×

# Chapter 6

9,884 views

Published on

C++ - 7 edition - Solution Manual

Published in: Technology
1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
9,884
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
102
0
Likes
1
Embeds 0
No embeds

No notes for slide

### Chapter 6

1. 1. 6Functions and anIntroduction to Recursion:Solutions Form ever follows function. —Louis Henri Sullivan E pluribus unum. (One composed of many.) —Virgil O! call back yesterday, bid time return. —William Shakespeare Answer me in one word. —William Shakespeare There is a point at which methods devour themselves. —Frantz Fanon Objectives In this chapter you’ll learn: ■ To construct programs modularly from functions. ■ To use common math library functions. ■ The mechanisms for passing data to 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 game-playing applications. ■ How the visibility of identifiers is limited to specific regions of programs. ■ To write and use recursive functions. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
3. 3. Student Solution Exercises 334 } // end if3536 // calculate current cars parking charge37 currentCharge = calculateCharges( hour );38 totalCharges += currentCharge; // update total charges3940 // display row data for current car41 cout << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour42 << setw( 14 ) << setprecision( 2 ) << currentCharge << "n";43 } // end for4445 // display row data for totals46 cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )47 << totalHours << setw( 14 ) << setprecision( 2 )48 << totalCharges << endl;49 } // end main5051 // calculateCharges returns charge according to number of hours52 double calculateCharges( double hours )53 {54 double charge; // calculated charge5556 if ( hours < 3.0 ) // \$2 for up to 3 hours57 charge = 2.0;58 else // \$.50 for each extra hour59 charge = 2.0 + .5 * ceil( hours - 3.0 );6061 // return charge, ensuring charge is not over \$10.0062 return ( charge > 10.0 ? 10.0 : charge );63 } // 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 (Rounding Numbers) 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 // Exercise 6.13 Solution: Ex06_13.cpp2 // Rounding numbers using floor.3 #include <iostream>4 #include <iomanip>5 #include <cmath> © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
4. 4. 4 Chapter 6 Functions and an Introduction to Recursion: Solutions 6 using namespace std; 7 8 double roundToIntegers( double ); // function prototype 910 int main()11 {12 double x; // current input13 double y; // current input rounded1415 cout << fixed; // set floating-point number format1617 // loop for 5 inputs18 for ( int loop = 1; loop <= 5; loop++ )19 {20 cout << "Enter a number: ";21 cin >> x;2223 y = roundToIntegers( x ); // y holds rounded input24 cout << setprecision( 6 ) << x << " rounded is "25 << setprecision( 1 ) << y << endl;26 } // end for27 } // end main2829 // roundToIntegers rounds 5 inputs30 double roundToIntegers( double value )31 {32 return floor( value + .5 );33 } // end function roundToIntegersEnter a number: 8.228.220000 rounded is 8.0Enter a number: 7.987.980000 rounded is 8.0Enter a number: 4.524.520000 rounded is 5.0Enter a number: 6.99996.999900 rounded is 7.0Enter a number: 3.3453.345000 rounded is 3.0 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() % 113; e) –1 ≤ n ≤ 1 ANS: n = rand() % 3 - 1; f) –3 ≤ n ≤ 11 ANS: n = rand() % 15 - 3; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
5. 5. Student Solution Exercises 5 6.18 (Exponentiation) 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. Do not use any math library functions. ANS: 1 // Exercise 6.18 Solution: Ex06_18.cpp 2 // Calculate exponentiation of integers. 3 #include <iostream> 4 using namespace std; 5 6 int integerPower( int, int ); // function prototype 7 8 int main() 9 {10 int exp; // integer exponent11 int base; // integer base1213 cout << "Enter base and exponent: ";14 cin >> base >> exp;15 cout << base << " to the power " << exp << " is: "16 << integerPower( base, exp ) << endl;17 } // end main1819 // integerPower calculates and returns b raised to the e power20 int integerPower( int b, int e )21 {22 int product = 1; // resulting product2324 // multiply product times b e number of times25 for ( int i = 1; i <= e; i++ )26 product *= b;2728 return product; // return resulting product29 } // end function integerPowerEnter base and exponent: 5 25 to the power 2 is: 25 6.20 (Multiples) Write a function multiple that determines for a pair of integers whether the sec- ond 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 // Exercise 6.20 Solution: Ex06_20.cpp2 // Determines whether, for a pair of integers,3 // the second is a multiple of the first.4 #include <iostream>5 using namespace std; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
6. 6. 6 Chapter 6 Functions and an Introduction to Recursion: Solutions 6 7 bool multiple( int, int ); // function prototype 8 9 int main()10 {11 int x; // first integer12 int y; // second integer1314 // loop 3 times15 for ( int i = 1; i <= 3; i++ )16 {17 cout << "Enter two integers: ";18 cin >> x >> y;1920 // determine if second is multiple of first21 if ( multiple( x, y ) )22 cout << y << " is a multiple of " << x << "nn";23 else24 cout << y << " is not a multiple of " << x << "nn";25 } // end for2627 cout << endl;28 } // end main2930 // multiple determines if b is multiple of a31 bool multiple( int a, int b )32 {33 return !( b % a );34 } // end function multipleEnter two integers: 3 44 is not a multiple of 3Enter two integers: 12 33 is not a multiple of 12Enter two integers: 3 1212 is a multiple of 3 6.22 (Square of Asterisks) 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:**************** © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
7. 7. Student Solution Exercises 7 ANS: 1 // Exercise 6.22 Solution: Ex06_22.cpp 2 // Displays a solid square of asterisks. 3 #include <iostream> 4 using namespace std; 5 6 void square( int ); // function prototype 7 8 int main() 9 {10 int side; // input side length1112 cout << "Enter side: ";13 cin >> side;14 cout << n;1516 square( side ); // display solid square of asterisks17 cout << endl;18 } // end main1920 // square displays solid square of asterisks with specified side21 void square( int side )22 {23 // loop side times for number of rows24 for ( int row = 1; row <= side; row++ )25 {26 // loop side times for number of columns27 for ( int col = 1; col <= side; col++ )28 cout << *;2930 cout << n;31 } // end for32 } // end function squareEnter side: 4**************** 6.26 (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. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
8. 8. 8 Chapter 6 Functions and an Introduction to Recursion: Solutions ANS: 1 // Exercise 6.26 Solution: Ex06_26.cpp 2 // Fahrenheit and Celsius equivalents. 3 #include <iostream> 4 #include <iomanip> 5 using namespace std; 6 7 int celsius( int ); // function prototype 8 int fahrenheit( int ); // function prototype 910 int main()11 {12 // display table of Fahrenheit equivalents of Celsius temperatures13 cout << "Fahrenheit equivalents of Celsius temperatures:" << endl;1415 // create 4 sets of table headers16 for ( int t = 0; t < 4; t++ )17 cout << setw( 7 ) << "Celsius" << setw( 12 ) << "Fahrenheit ";1819 cout << endl;2021 // display temperatures in blocks of 2522 for ( int i = 0; i < 25; i++ )23 {24 for ( int j = 0; j <= 75; j += 25 )25 cout << setw( 7 ) << i + j26 << setw( 11 ) << fahrenheit( i + j ) << ;2728 cout << endl;29 } // end for3031 // display equivalent for 10032 cout << setw( 64 ) << 100 << setw( 11 ) << fahrenheit( 100 ) << endl;3334 // display table of Celsius equivalents of Fahrenheit temperatures35 cout << "nCelsius equivalents of Fahrenheit temperatures:" << endl;3637 // create 4 sets of table headers38 for ( int t = 0; t < 4; t++ )39 cout << setw( 10 ) << "Fahrenheit" << setw( 9 ) << "Celsius ";4041 cout << endl;4243 // display temperatures in blocks of 4544 for ( int i = 32; i < 77; i++ )45 {46 for ( int j = 0; j <= 135; j += 45 )47 cout << setw( 10 ) << i + j48 << setw( 8 ) << celsius( i + j ) << ;4950 cout << endl;51 } // end for52 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
9. 9. Student Solution Exercises 953 // display equivalent for 21254 cout << setw( 67 ) << 212 << setw( 8 ) << celsius( 212 ) << endl;55 } // end main5657 // celsius returns Celsius equivalent of fTemp,58 // given in Fahrenheit59 int celsius( int fTemp )60 {61 return static_cast< int > ( 5.0 / 9.0 * ( fTemp - 32 ) );62 } // end function celsius6364 // fahrenheit returns Fahrenheit equivalent of cTemp,65 // given in Celsius66 int fahrenheit( int cTemp )67 {68 return static_cast< int > ( 9.0 / 5.0 * cTemp + 32 );69 } // end function fahrenheitFahrenheit 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 (Perfect Numbers) An integer is said to be a perfect number if the sum of its divisors, includ- ing 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, be- cause 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 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
10. 10. 10 Chapter 6 Functions and an Introduction to Recursion: Solutions 1 and 1000. Print the divisors 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 // Exercise 6.28 Solution: Ex06_28.cpp 2 // Determine perfect numbers between 1 and 1000. 3 // A number is perfect if it is equal to the sum of its factors. 4 #include <iostream> 5 using namespace std; 6 7 bool isPerfect( int ); // function prototype 8 void printSum( int ); // function prototype 910 int main()11 {12 cout << "Perfect integers between 1 and 1000:" << endl;1314 // loop from 2 to 100015 for ( int j = 2; j <= 1000; j++ )16 {17 // if current integer is perfect18 if ( isPerfect( j ) )19 printSum( j ); // print it as sum of factors20 } // end for2122 cout << endl;23 } // end main2425 // isPerfect returns true if value is perfect integer,26 // i.e., if value is equal to sum of its factors27 bool isPerfect( int value )28 {29 int factorSum = 1; // current sum of factors3031 // loop through possible factor values32 for ( int i = 2; i <= value / 2; i++ )33 {34 // if i is factor35 if ( value % i == 0 )36 factorSum += i; // add to sum37 } // end for3839 // return true if value is equal to sum of factors40 return factorSum == value;41 } // end function isPerfect4243 // printSum displays value followed by factors in summation form44 void printSum( int value )45 {46 cout << value << " = 1";4748 // loop through possible factor values49 for ( int i = 2; i <= value / 2; i++ )50 { © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
11. 11. Student Solution Exercises 1151 // if i is factor52 if ( value % i == 0 )53 cout << " + " << i; // display as part of sum54 } // end for5556 cout << endl;57 } // end function printSumPerfect integers between 1 and 1000:6 = 1 + 2 + 328 = 1 + 2 + 4 + 7 + 14496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 6.32 Write a function qualityPoints that inputs a student’s average and returns 4 if a student’s average is 90–100, 3 if the average is 80–89, 2 if the average is 70–79, 1 if the average is 60–69 and 0 if the average is lower than 60. ANS:1 // Exercise 6.32 Solution: Ex06_32.cpp2 // Determine quality points on 0 to 4 scale 3 // for averages in 0 to 100 range. 4 #include <iostream> 5 using namespace std; 6 7 int qualityPoints( int ); // function prototype 8 9 int main()10 {11 int average; // current average1213 // loop for 5 inputs14 for ( int loop = 1; loop <= 5; loop++ )15 {16 cout << "nEnter the students average: ";17 cin >> average;1819 // determine and display corresponding quality points20 cout << average << " on a 4 point scale is "21 << qualityPoints( average ) << endl;22 } // end for2324 cout << endl;25 } // end main2627 // qualityPoints takes average in range 0 to 100 and28 // returns corresponding quality points on 0 to 4 scale29 int qualityPoints( int average )30 {31 if ( average >= 90 ) // 90 <= average <= 10032 return 4;33 else if ( average >= 80 ) // 80 <= average <= 89 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.