Chapter 6

9,884 views

Published on

C++ - 7 edition - Solution Manual

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
9,884
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
102
Comments
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.
  2. 2. 2 Chapter 6 Functions and an Introduction to Recursion: Solutions Student Solution Exercises 6.12 (Parking Charges) 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 print the total of yesterday’s receipts. The program should use the function calculateCharges to determine the charge for each customer. Your outputs should appear in the following format:Car Hours Charge1 1.5 2.002 4.0 2.503 24.0 10.00TOTAL 29.5 14.50 ANS: 1 // Exercise 6.12 Solution: Ex06_12.cpp 2 // Calculate charges for 3 cars at parking garage. 3 #include <iostream> 4 #include <iomanip> 5 #include <cmath> 6 using namespace std; 7 8 double calculateCharges( double ); // function prototype 910 int main()11 {12 double hour; // number of hours for current car13 double currentCharge; // parking charge for current car14 double totalCharges = 0.0; // total charges15 double totalHours = 0.0; // total number of hours16 bool first = true; // used for printing table headers1718 cout << fixed; // set floating-point number format19 cout << "Enter the hours parked for 3 cars: ";2021 // loop 3 times for 3 cars22 for ( int i = 1; i <= 3; i++ )23 {24 cin >> hour;25 totalHours += hour; // add current hours to total hours2627 // if first time through loop, display headers28 if ( first )29 {30 cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"31 << setw( 15 ) << "Chargen";3233 first = false; // prevent from printing again © 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.
  12. 12. 12 Chapter 6 Functions and an Introduction to Recursion: Solutions34 return 3;35 else if ( average >= 70 ) // 70 <= average <= 7936 return 2;37 else if ( average >= 60 ) // 60 <= average <= 6938 return 1;39 else // 0 <= average < 6040 return 0;41 } // end function qualityPointsEnter the students average: 9999 on a 4 point scale is 4Enter the students average: 7272 on a 4 point scale is 2Enter the students average: 8888 on a 4 point scale is 3Enter the students average: 6565 on a 4 point scale is 1Enter the students average: 3333 on a 4 point scale is 0 6.34 (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 player’s 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 // Exercise 6.34 Solution: Ex06_34.cpp2 // Randomly generate numbers between 1 and 1000 for user to guess.3 #include <iostream>4 #include <cstdlib>5 #include <ctime>6 using namespace std;7 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  13. 13. Student Solution Exercises 13 8 void guessGame(); // function prototype 9 bool isCorrect( int, int ); // function prototype1011 int main()12 {13 srand( time( 0 ) ); // seed random number generator14 guessGame();15 } // end main1617 // guessGame generates numbers between 1 and 1000 and checks users guess18 void guessGame()19 {20 int answer; // randomly generated number21 int guess; // users guess22 char response; // y or n response to continue game2324 // loop until user types n to quit game25 do26 {27 // generate random number between 1 and 100028 // 1 is shift, 1000 is scaling factor29 answer = 1 + rand() % 1000;3031 // prompt for guess32 cout << "I have a number between 1 and 1000.n"33 << "Can you guess my number?n"34 << "Please type your first guess." << endl << "? ";35 cin >> guess;3637 // loop until correct number38 while ( !isCorrect( guess, answer ) )39 cin >> guess;4041 // prompt for another game42 cout << "nExcellent! You guessed the number!n"43 << "Would you like to play again (y or n)? ";44 cin >> response;4546 cout << endl;47 } while ( response == y );48 } // end function guessGame4950 // isCorrect returns true if g equals a51 // if g does not equal a, displays hint52 bool isCorrect( int g, int a )53 {54 // guess is correct55 if ( g == a )56 return true;5758 // guess is incorrect; display hint59 if ( g < a )60 cout << "Too low. Try again.n? ";61 else © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  14. 14. 14 Chapter 6 Functions and an Introduction to Recursion: Solutions62 cout << "Too high. Try again.n? ";6364 return false;65 } // end function isCorrectI have a number between 1 and 1000.Can you guess my number?Please type your first guess.? 500Too high. Try again.? 250Too low. Try again.? 375Too low. Try again.? 438Too high. Try again.? 405Too high. Try again.? 380Too low. Try again.? 393Too low. Try again.? 399Too high. Try again.? 396Too low. Try again.? 398Too high. Try again.? 397Excellent! You guessed the number!Would you like to play again (y or n)? n 6.36 (Recursive Exponentiation) 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 // Exercise 6.36 Solution: Ex06_36.cpp2 // Recursive exponentiation.3 #include <iostream>4 using namespace std;56 long power( long, long ); // function prototype7 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  15. 15. Student Solution Exercises 15 8 int main() 9 {10 long b; // base11 long e; // exponent1213 cout << "Enter a base and an exponent: ";14 cin >> b >> e;1516 // calculate and display b^e17 cout << b << " raised to the " << e << " is " << power( b, e ) << endl;18 } // end main1920 // power recursively calculates base^exponent, assume exponent >= 121 long power( long base, long exponent )22 {23 if ( exponent == 1 ) // base case: exponent equals 1, return base24 return base;25 else // recursion step26 return base * power( base, exponent - 1 );27 } // end function powerEnter a base and an exponent: 3 43 raised to the 4 is 81 6.40 (Visualizing Recursion) It’s 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: 1 // Exercise 6.40 Solution: Ex06_40.cpp 2 // Visualizing recursion with factorial function. 3 #include <iostream> 4 #include <iomanip> 5 using namespace std; 6 7 unsigned long factorial( unsigned long ); // function prototype 8 9 int main()10 {11 // Loop 10 times. During each iteration, calculate12 // factorial( i ) and display result.13 for ( int i = 0; i <= 10; i++ )14 {15 cout << "Calculating factorial ( " << i << " )" << endl;16 unsigned long result = factorial( i );17 cout << setw( 2 ) << i << "! = " << result << endl << endl;18 } // end for19 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  16. 16. 16 Chapter 6 Functions and an Introduction to Recursion: Solutions2021 // recursive definition of function factorial22 unsigned long factorial( unsigned long number )23 {24 if ( number <= 1 ) // base case25 {26 cout << " Reached base case of 1" << endl;27 return 1;28 } // end if29 else // recursion step30 {31 // add outputs and indentation to help visualize recursion32 cout << setw( number * 3 ) << ""33 << "local variable number: " << number << endl;34 cout << setw( number * 3 ) << ""35 << "recursively calling factorial( "36 << number - 1 << " )" << endl << endl;37 return ( number * factorial( number - 1 ) );38 } // end else39 } // end function factorial © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  17. 17. Student Solution Exercises 17Calculating factorial ( 0 ) Reached base case of 1 0! = 1Calculating factorial ( 1 ) Reached base case of 1 1! = 1Calculating 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 110! = 36288006.43 (Distance Between Points) Write function distance that calculates the distance betweentwo points (x1, y1) and (x2, y2). All numbers and return values should be of type double. ANS:1 // Exercise 6.43 Solution: Ex06_43.cpp2 // Calculate distance between 2 points.3 #include <iostream> © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  18. 18. 18 Chapter 6 Functions and an Introduction to Recursion: Solutions 4 #include <iomanip> 5 #include <cmath> 6 using namespace std; 7 8 double distance( double, double, double, double ); // function prototype 910 int main()11 {12 double x1; // x coordinate of first point13 double y1; // y coordinate of first point14 double x2; // x coordinate of second point15 double y2; // y coordinate of second point1617 // prompt for first point coordinates18 cout << "Enter the first point: ";19 cin >> x1 >> y1;2021 // prompt for second point coordinates22 cout << "Enter the second point: ";23 cin >> x2 >> y2;2425 // calculate and display distance26 cout << fixed << "Distance between (" << setprecision( 1 ) << x127 << ", " << y1 << ") and (" << x2 << ", " << y2 << ") is "28 << distance( x1, y1, x2, y2 ) << endl;29 } // end main3031 // distance calculates distance between 2 points32 // given by (a1, b1) and (a2, b2)33 double distance( double a1, double b1, double a2, double b2 )34 {35 return sqrt( pow( a1 - a2, 2 ) + pow( b1 - b2, 2 ) );36 } // end function distanceEnter the first point: 8 9Enter the second point: 0 1Distance between (8.0, 9.0) and (0.0, 1.0) is 11.3 6.48 (Find the Error) Find the error in each of the following program segments and explain how to correct it: a) float cube( float ); // function prototype 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 function definition. b) register auto int x = 7; ANS: Error: Only one storage class specifier can be used. Correction: Remove either register or auto. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  19. 19. Student Solution Exercises 19 c) int randomNumber = srand(); ANS: Error: Function srand takes an unsigned argument and does not return a value. Correction: Use rand instead of srand. d) float y = 123.45678; int x; 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 and remove the now-redundant static_cast. 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 sum( n ) to sum( n - 1 ). 6.51 (Pass-by-Value vs. Pass-by-Reference) Write a complete C++ program with the two alternate functions specified below, each of which 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 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: 1 // Exercise 6.51 Solution: Ex06_51.cpp 2 // Comparing call by value and call by reference. 3 #include <iostream> 4 using namespace std; 5 6 int tripleByValue( int ); // function prototype 7 void tripleByReference( int & ); // function prototype 8 9 int main()10 {11 int count; // local variable for testing1213 // prompt for count value14 cout << "Enter a value for count: "; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  20. 20. 20 Chapter 6 Functions and an Introduction to Recursion: Solutions15 cin >> count;1617 // using call by value18 cout << "nValue of count before call to tripleByValue() is: "19 << count << "nValue returned from tripleByValue() is: "20 << tripleByValue( count )21 << "nValue of count (in main) after tripleCallByValue() is: "22 << count;2324 // using call by reference25 cout << "nnValue of count before call to tripleByReference() is: "26 << count << endl;2728 tripleByReference( count );2930 cout << "Value of count (in main) after call to "31 << "tripleByReference() is: " << count << endl;32 } // end main3334 // tripleByValue uses call-by-value parameter passing to triple the value35 int tripleByValue( int value )36 {37 return value *= 3;38 } // end function tripleByValue3940 // tripleByReference uses call-by-reference parameter passing41 // to triple the variable referenced by valueRef42 void tripleByReference( int &valueRef )43 {44 valueRef *= 3;45 } // end function tripleByReferenceEnter a value for count: 8Value of count before call to tripleByValue() is: 8Value returned from tripleByValue() is: 24Value of count (in main) after tripleCallByValue() is: 8Value of count before call to tripleByReference() is: 8Value of count (in main) after call to tripleByReference() is: 24 6.53 (Function Template minimum) Write a program that uses a function template called minimum to determine the smaller of two arguments. Test the program using integer, character and floating- point number arguments. ANS:1 // Exercise 6.53 Solution: Ex06_53.cpp2 // Finding the minimum using a function template.3 #include <iostream>4 using namespace std;56 // definition of function template minimum; finds the smaller of 2 values © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  21. 21. Student Solution Exercises 21 7 template < class T > 8 T minimum( T value1, T value2 ) 9 {10 if ( value1 < value2 )11 return value1;12 else13 return value2;14 } // end function template minimum1516 int main()17 {18 // demonstrate minimum with int values19 int int1; // first int value20 int int2; // second int value2122 cout << "Input two integer values: ";23 cin >> int1 >> int2;2425 // invoke int version of minimum26 cout << "The smaller integer value is: " << minimum( int1, int2 );2728 // demonstrate minimum with char values29 char char1; // first char value30 char char2; // second char value3132 cout << "nnInput two characters: ";33 cin >> char1 >> char2;3435 // invoke char version of minimum36 cout << "The smaller character value is: " << minimum( char1, char2 );3738 // demonstrate minimum with double values39 double double1; // first double value40 double double2; // second double value4142 cout << "nnInput two double values: ";43 cin >> double1 >> double2;4445 // invoke double version of minimum46 cout << "The smaller double value is: " << minimum( double1, double2 )47 << endl;48 } // end mainInput two integer values: 7 54The smaller integer value is: 7Input two characters: x eThe smaller character value is: eInput two double values: 8.46 4.35The smaller double value is: 4.35 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

×