Chapter 5

2,562 views
2,332 views

Published on

C++ - 7 edition - Solution Manual

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,562
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
80
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Chapter 5

  1. 1. Control Statements, Part 2:Solutions 5 Not everything that can be counted counts, and not every thing that counts can be counted. —Albert Einstein Who can control his fate? —William Shakespeare The used key is always bright. —Benjamin Franklin Intelligence … is the faculty of making artificial objects, especially tools to make tools. —Henri Bergson Objectives In this chapter you’ll learn: ■ The essentials of counter- controlled repetition. ■ To use for and do…while to execute statements in a program repeatedly. ■ To implement multiple selection using the switch selection statement. ■ How break and continue alter the flow of control. ■ To use the logical operators to form complex conditional expressions in control statements. ■ To avoid the consequences of confusing the equality and assignment operators. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  2. 2. 2 Chapter 5 Control Statements, Part 2: Solutions Student Solution Exercises 5.4 Find the error(s), if any, in each of the following: a) For ( x = 100, x >= 1, x++ ) cout << x << endl; ANS: For should be for. The commas should be semicolons. The ++ should be a decrement such as --. b) The following code should print whether integer value is odd or even: switch ( value % 2 ) { case 0: cout << "Even integer" << endl; case 1: cout << "Odd integer" << endl; } ANS: case 0 needs a break statement. c) The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 ) cout << x << endl; ANS: += should be -=. d) The following code should output the even integers from 2 to 100: counter = 2; do { cout << counter << endl; counter += 2; } While ( counter < 100 ); ANS: While should be while. Operator < should be <=. 5.5 (Summing Integers) Write a program that uses a for statement to sum a sequence of inte- gers. Assume that the first integer read specifies the number of values remaining to be entered. Your program should read only one value per input statement. A typical input sequence might be 5 100 200 300 400 500 where the 5 indicates that the subsequent 5 values are to be summed. ANS: 1 // Exercise 5.5 Solution: ex05_05.cpp 2 // Total a sequence of integers. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int total = 0; // current total 9 int number; // number of values10 int value; // current value11 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  3. 3. Student Solution Exercises 312 // display prompt13 cout << "Enter the number of values to be summed "14 << "followed by the values: n";15 cin >> number; // input number of values1617 // loop number times18 for ( int i = 1; i <= number; i++ )19 {20 cin >> value;21 total += value;22 } // end for2324 // display total25 cout << "Sum of the " << number << " values is " << total << endl;26 } // end mainEnter the number of values to be summed followed by the values:5 100 200 300 400 500Sum of the 5 values is 1500 5.8 (Find the Smallest Integer) Write a program that uses a for statement to find the smallest of several integers. Assume that the first value read specifies the number of values remaining. ANS: 1 // Exercise 5.8 Solution: ex05_08.cpp 2 // Find the smallest of several integers. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int number; // number of values 9 int value; // current value10 int smallest; // smallest value so far1112 cout << "Enter the number of integers to be processed ";13 cout << "followed by the integers: " << endl;14 cin >> number >> smallest;1516 // loop (number -1) times17 for ( int i = 2; i <= number; i++ )18 {19 cin >> value; // read in next value2021 // if current value less than smallest, update smallest22 if ( value < smallest )23 smallest = value;24 } // end for2526 // display smallest integer27 cout << "nThe smallest integer is: " << smallest << endl;28 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  4. 4. 4 Chapter 5 Control Statements, Part 2: SolutionsEnter the number of integers to be processed followed by the integers:6 10 3 15 21 26 14The smallest integer is: 3 5.10 (Factorials) The factorial function is used frequently in probability problems. Write a pro- gram that uses a for statement to evaluate the factorials of the integers from 1 to 5. Print the results in tabular format. What difficulty might prevent you from calculating the factorial of 20? ANS: Calculating the factorial of 20 might be difficult, because it might be such a large number that it would not fit in an int or long variable. 1 // Exercise 5.10 Solution: ex05_10.cpp 2 // Factorial program. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int factorial = 1; // current factorial value 910 // display table headers11 cout << "xtx!n";1213 // display factorial of numbers 1-514 for ( int i = 1; i <= 5; i++ )15 {16 factorial *= i; // i!1718 // display factorial value in table19 cout << i << t << factorial << n;20 } // end for2122 cout << endl;23 } // end mainx x!1 12 23 64 245 120 5.13 (Bar Chart) One interesting application of computers is drawing graphs and bar charts. Write a program that reads five numbers (each between 1 and 30). Assume that the user enters only valid values. For each number that is read, your program should print a line containing that number of adjacent asterisks. For example, if your program reads the number 7, it should print *******. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  5. 5. Student Solution Exercises 5 ANS: 1 // Exercise 5.13 Solution: ex05_13.cpp 2 // Displaying bar charts using asterisks. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int number; // current number 910 cout << "Enter 5 numbers between 1 and 30: ";1112 // loop 5 times13 for ( int i = 1; i <= 5; i++ )14 {15 cin >> number; // get a number from the user1617 // print asterisks corresponding to current input18 for ( int j = 1; j <= number; j++ )19 cout << *;2021 cout << endl;22 } // end for2324 cout << endl;25 } // end mainEnter 5 numbers between 1 and 30: 16 12 8 27 9************************************************************************ 5.15 (GradeBook Modification) Modify the GradeBook program of Fig. 5.9–Fig. 5.11 to calculate the grade-point average. A grade of A is worth 4 points, B is worth 3 points, and so on. ANS: 1 // Exercise 5.15 Solution: GradeBook.h 2 // Definition of class GradeBook that counts A, B, C, D and F grades. 3 // Member functions are defined in GradeBook.cpp 4 #include <string> // program uses C++ standard string class 5 using namespace std; 6 7 // GradeBook class definition 8 class GradeBook 9 {10 public:11 GradeBook( string ); // constructor initializes course name12 void setCourseName( string ); // function to set the course name13 string getCourseName(); // function to retrieve the course name © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  6. 6. 6 Chapter 5 Control Statements, Part 2: Solutions14 void displayMessage(); // display a welcome message15 void inputGrades(); // input arbitrary number of grades from user16 void displayGradeReport(); // display a report based on the grades17 private:18 string courseName; // course name for this GradeBook19 int aCount; // count of A grades20 int bCount; // count of B grades21 int cCount; // count of C grades22 int dCount; // count of D grades23 int fCount; // count of F grades24 }; // end class GradeBook 1 // Exercise 5.15 Solution: GradeBook.cpp 2 // Member-function definitions for class GradeBook that 3 // uses a switch statement to count A, B, C, D and F grades. 4 #include <iostream> 5 #include <iomanip> // parameterized stream manipulators 6 #include "GradeBook.h" 7 using namespace std; 8 9 // constructor initializes courseName with string supplied as argument;10 // initializes counter data members to 011 GradeBook::GradeBook( string name )12 {13 setCourseName( name ); // validate and store courseName14 aCount = 0; // initialize count of A grades to 015 bCount = 0; // initialize count of B grades to 016 cCount = 0; // initialize count of C grades to 017 dCount = 0; // initialize count of D grades to 018 fCount = 0; // initialize count of F grades to 019 } // end GradeBook constructor2021 // function to set the course name; limits name to 25 or fewer characters22 void GradeBook::setCourseName( string name )23 {24 if ( name.length() <= 25 ) // if name has 25 or fewer characters25 courseName = name; // store the course name in the object26 else // if name is longer than 25 characters27 { // set courseName to first 25 characters of parameter name28 courseName = name.substr( 0, 25 ); // select first 25 characters29 cout << "Name "" << name << "" exceeds maximum length (25).n"30 << "Limiting courseName to first 25 characters.n" << endl;31 } // end if...else32 } // end function setCourseName3334 // function to retrieve the course name35 string GradeBook::getCourseName()36 {37 return courseName;38 } // end function getCourseName3940 // display a welcome message to the GradeBook user41 void GradeBook::displayMessage() © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  7. 7. Student Solution Exercises 742 {43 // this statement calls getCourseName to get the44 // name of the course this GradeBook represents45 cout << "Welcome to the grade book forn" << getCourseName() << "!n"46 << endl;47 } // end function displayMessage4849 // input arbitrary number of grades from user; update grade counter50 void GradeBook::inputGrades()51 {52 int grade; // grade entered by user5354 cout << "Enter the letter grades." << endl55 << "Enter the EOF character to end input." << endl;5657 // loop until user types end-of-file key sequence58 while ( ( grade = cin.get() ) != EOF )59 {60 // determine which grade was input61 switch ( grade ) // switch statement nested in while62 {63 case A: // grade was uppercase A64 case a: // or lowercase a65 aCount++; // increment aCount66 break; // exit switch6768 case B: // grade was uppercase B69 case b: // or lowercase b70 bCount++; // increment bCount71 break; // exit switch7273 case C: // grade was uppercase C74 case c: // or lowercase c75 cCount++; // increment cCount76 break; // exit switch7778 case D: // grade was uppercase D79 case d: // or lowercase d80 dCount++; // increment dCount81 break; // exit switch8283 case F: // grade was uppercase F84 case f: // or lowercase f85 fCount++; // increment fCount86 break; // exit switch8788 case n: // ignore newlines,89 case t: // tabs,90 case : // and spaces in input91 break; // exit switch9293 default: // catch all other characters94 cout << "Incorrect letter grade entered."95 << " Enter a new grade.n"; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  8. 8. 8 Chapter 5 Control Statements, Part 2: Solutions96 break; // optional; will exit switch anyway97 } // end switch98 } // end while99 } // end function inputGrades100101 // display a report based on the grades entered by user102 void GradeBook::displayGradeReport()103 {104 // display summary of results105 cout << "nnNumber of students who received each letter grade:"106 << "nA: " << aCount // display number of A grades107 << "nB: " << bCount // display number of B grades108 << "nC: " << cCount // display number of C grades109 << "nD: " << dCount // display number of D grades110 << "nF: " << fCount // display number of F grades111 << endl;112113 // calculate total grades114 int gradeCount = aCount + bCount + cCount + dCount + fCount;115116 // display class average117 // if user entered at least one grade118 if ( gradeCount != 0 )119 {120 // calculate total grades121 int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;122123 // set floating-point number format124 cout << fixed << setprecision( 1 );125126 // compute and display class GPA with 1 digit of precision127 cout << "nThe class average is: "128 << static_cast< double > ( gradeTotal ) / gradeCount129 << endl;130 } // end if131 } // end function displayGradeReport 1 // Exercise 5.15 Solution: ex05_15.cpp 2 // Create GradeBook object, input grades and display grade report. 3 4 // include definition of class GradeBook from GradeBook.h 5 #include "GradeBook.h" 6 7 int main() 8 { 9 // create GradeBook object myGradeBook and10 // pass course name to constructor11 GradeBook myGradeBook( "CS101 C++ Programming" );1213 myGradeBook.displayMessage(); // display welcome message14 myGradeBook.inputGrades(); // read grades from user15 myGradeBook.displayGradeReport(); // display report based on grades16 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  9. 9. Student Solution Exercises 9Welcome to the grade book forCS101 C++ Programming!Enter the letter grades.Enter the EOF character to end input.aAAaCEIncorrect letter grade entered. Enter a new grade.F^ZNumber of students who received each letter grade:A: 4B: 0C: 1D: 0F: 1The class average is: 3.0 5.18 (Number Systems Table) Write a program that prints a table of the binary, octal and hexa- decimal equivalents of the decimal numbers in the range 1–256. If you are not familiar with these number systems, read Appendix D, Number Systems, first. [Hint: You can use the stream manipu- lators dec, oct and hex to display integers in decimal, octal and hexadecimal formats, respectively.] ANS: 1 // Exercise 5.18 Solution: ex05_18.cpp 2 // Display decimal, binary, octal and hexadecimal numbers. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int number; // loop counter for binary numbers 9 int factor; // current factor for binary numbers1011 // use tabs to display table headers12 cout << "DecimalttBinaryttOctaltHexadecimaln";1314 // loop from 1 to 25615 for ( int loop = 1; loop <= 256; loop++ )16 {17 cout << dec << loop << "tt";1819 // output binary number20 // initialize variables for calculating binary equivalent21 number = loop;22 factor = 256; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  10. 10. 10 Chapter 5 Control Statements, Part 2: Solutions2324 // output first digit25 cout << ( number == 256 ? 1 : 0 );2627 // loop until factor is 1, i.e., last digit28 do29 {30 // output current digit31 cout <<32 ( number < factor && number >= ( factor / 2 ) ? 1 : 0 );3334 // update factor and number variables35 factor /= 2;36 number %= factor;37 } while ( factor > 1 );3839 // output octal number using oct stream manipulator40 cout << t << oct << loop;4142 // output hexadecimal number using hex stream manipulator43 cout << t << hex << loop << endl;44 } // end for45 } // end mainDecimal Binary Octal Hexadecimal1 000000001 1 12 000000010 2 23 000000011 3 34 000000100 4 45 000000101 5 5...251 011111011 373 fb252 011111100 374 fc253 011111101 375 fd254 011111110 376 fe255 011111111 377 ff256 100000000 400 100 5.21 (Calculating Salaries) A company pays its employees as managers (who receive a fixed weekly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they work and “time-and-a-half”—1.5 times their hourly wage—for overtime hours worked), commission workers (who receive $250 plus 5.7 percent of their gross weekly sales), or pieceworkers (who receive a fixed amount of money per item for each of the items they produce—each pieceworker in this company works on only one type of item). Write a program to compute the weekly pay for each employee. You do not know the number of employees in advance. Each type of employee has its own pay code: Man- agers have code 1, hourly workers have code 2, commission workers have code 3 and pieceworkers have code 4. Use a switch to compute each employee’s pay according to that employee’s paycode. Within © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  11. 11. Student Solution Exercises 11 the switch, prompt the user (i.e., the payroll clerk) to enter the appropriate facts your program needs to calculate each employee’s pay according to that employee’s paycode. ANS: 1 // Exercise 5.21 Solution: ex05_21.cpp 2 // Calculate wages for each employee. 3 #include <iostream> 4 #include <iomanip> // parameterized stream manipulators 5 using namespace std; 6 7 int main() 8 { 9 int payCode; // current employees pay code10 int pieces; // current pieceworkers number of pieces11 double salary; // current employees salary12 double hours; // current hourly employees hours13 double pay; // current employees weekly pay1415 // prompt for first employee input16 cout << "Enter paycode (-1 to end): ";17 cin >> payCode;1819 // set floating-point number format20 cout << fixed << setprecision( 2 );2122 // loop until sentinel value read from user23 while ( payCode != -1 )24 {25 // switch to appropriate computation according to pay code26 switch ( payCode )27 {28 case 1: // pay code 1 corresponds to manager29 // prompt for weekly salary30 cout << "Manager selected.nEnter weekly salary: ";31 cin >> salary;3233 // managers pay is weekly salary34 cout << "The managers pay is $" << salary << n;35 break; // exit switch3637 case 2: // pay code 2 corresponds to hourly worker38 // prompt for hourly salary39 cout << "Hourly worker selected.n"40 << "Enter the hourly salary: ";41 cin >> salary;4243 // prompt for number of hours worked44 cout << "Enter the total hours worked: ";45 cin >> hours;4647 // pay fixed for up to 40 hours48 // 1.5 for hours over 4049 pay = ( hours > 40.0 ? ( hours - 40 ) * 1.5 * salary50 + salary * 40.0 : salary * hours ); © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  12. 12. 12 Chapter 5 Control Statements, Part 2: Solutions5152 // display current employees pay53 cout << "Workers pay is $" << pay << n;54 break; // exit switch5556 case 3: // pay code 3 corresponds to commission worker57 // prompt for gross weekly sales58 cout << "Commission worker selected.n"59 << "Enter gross weekly sales: ";60 cin >> salary;6162 // pay $250 plus 5.7% of gross weekly sales63 pay = 250.0 + 0.057 * salary;6465 // display current employees pay66 cout << "Commission workers pay is $" << pay << n;67 break; // exit switch6869 case 4: // pay code 4 corresponds to pieceworker70 // prompt for number of pieces71 cout << "Pieceworker selected.n"72 << "Enter number of pieces: ";73 cin >> pieces;7475 // prompt for wage per piece76 cout << "Enter wage per piece: ";77 cin >> salary;7879 pay = pieces * salary; // compute pay8081 // display current employees pay82 cout << "Pieceworkers pay is $" << pay << n;83 break; // exit switch8485 default: // default case86 cout << "Invalid pay code.n";87 break;88 } // end switch8990 // prompt for next employee input91 cout << "nEnter paycode (-1 to end): ";92 cin >> payCode;93 } // end while94 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  13. 13. Student Solution Exercises 13Enter paycode (-1 to end): 1Manager selected.Enter weekly salary: 1200The managers pay is $ 1200.00Enter paycode (-1 to end): 2Hourly worker selected.Enter the hourly salary: 9.50Enter the total hours worked: 20Workers pay is $ 190.00Enter paycode (-1 to end): 3Commission worker selected.Enter gross weekly sales: 4000Commission workers pay is $ 478.00Enter paycode (-1 to end): 4Pieceworker selected.Enter number of pieces: 50Enter wage per piece: 3Pieceworkers pay is $ 150.00Enter paycode (-1 to end): -1 5.23 (Diamond of Asterisks) Write a program that prints the following diamond shape. You may use output statements that print a single asterisk (*), a single blank or a single newline. Maximize your use of repetition (with nested for statements) and minimize the number of output statements. * *** ***** **************** ******* ***** *** * ANS: 1 // Exercise 5.23 Solution: ex05_23.cpp 2 // Drawing a diamond shape with asterisks using nested control statements. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 // top half 9 for ( int row = 1; row <= 5; row++ )10 {11 // print preceding spaces12 for ( int space = 1; space <= 5 - row; space++ )13 cout << ; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  14. 14. 14 Chapter 5 Control Statements, Part 2: Solutions1415 // print asterisks16 for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ )17 cout << *;1819 cout << n;20 } // end for2122 // bottom half23 for ( int row = 4; row >= 1; row-- )24 {25 // print preceding spaces26 for ( int space = 1; space <= 5 - row; space++ )27 cout << ;2829 // print asterisks30 for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ )31 cout << *;3233 cout << n;34 } // end for3536 cout << endl;37 } // end main * *** ***** **************** ******* ***** *** * 5.26 What does the following program segment do? 1 for ( int i = 1; i <= 5; i++ ) 2 { 3 for ( int j = 1; j <= 3; j++ ) 4 { 5 for ( int k = 1; k <= 4; k++ ) 6 cout << *; 7 8 cout << endl; 9 } // end inner for1011 cout << endl;12 } // end outer for © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  15. 15. Student Solution Exercises 15 ANS: 1 // Exercise 5.26 Solution: ex05_26.cpp 2 // Prints 5 groups of 3 lines, each containing 4 asterisks. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 for ( int i = 1; i <= 5; i++ ) 9 {10 for ( int j = 1; j <= 3; j++ )11 {12 for ( int k = 1; k <= 4; k++ )13 cout << *;1415 cout << endl;16 } // end inner for1718 cout << endl;19 } // end outer for20 } // end main************************************************************ 5.27 (Removing the continue Statement) Describe in general how you’d remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the tech- nique you developed here to remove the continue statement from the program of Fig. 5.14. ANS: A loop can be rewritten without a continue statement by moving all the code that appears in the body of the loop after the continue statement to an if statement that tests for the opposite of the continue condition. Thus, the code that was originally after the continue statement executes only when the if statement’s conditional ex- © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
  16. 16. 16 Chapter 5 Control Statements, Part 2: Solutions pression is true (i.e., the “continue” condition is false). When the “continue” condi- tion is true, the body of the if does not execute and the program “continues” to the next iteration of the loop by not executing the remaining code in the loop’s body. 1 // Exercise 5.27 Solution: ex05_27.cpp 2 // Structured equivalent for continue statement. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 for ( int count = 1; count <= 10; count++ ) // loop 10 times 9 {10 if ( count != 5 ) // if count == 5, skip to next iteration11 cout << count << " ";12 } // end for1314 cout << "nUsed if condition to skip printing 5" << endl;15 } // end main1 2 3 4 6 7 8 9 10Used if condition to skip printing 5 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

×