Chapter 5

16
5 Control Statements, Part 2: Solutions 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 dowhile 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.

description

C++ - 7 edition - Solution Manual

Transcript of Chapter 5

Page 1: Chapter 5

5Control Statements, Part 2:Solutions

Not everything that can becounted counts, and not everything that counts can becounted.—Albert Einstein

Who can control his fate?—William Shakespeare

The used key is always bright.—Benjamin Franklin

Intelligence … is the faculty ofmaking artificial objects,especially tools to make tools.—Henri Bergson

O b j e c t i v e sIn this chapter you’ll learn:

■ The essentials of counter-controlled repetition.

■ To use for and do…whileto execute statements in aprogram repeatedly.

■ To implement multipleselection using the switchselection statement.

■ How break and continuealter the flow of control.

■ To use the logical operatorsto form complex conditionalexpressions in controlstatements.

■ To avoid the consequences ofconfusing the equality andassignment operators.

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 2: Chapter 5

2 Chapter 5 Control Statements, Part 2: Solutions

Student Solution Exercises5.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 decrementsuch 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. Yourprogram 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.cpp2 // Total a sequence of integers.3 #include <iostream>4 using namespace std;56 int main()7 {8 int total = 0; // current total9 int number; // number of values

10 int value; // current value11

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 3: Chapter 5

Student Solution Exercises 3

5.8 (Find the Smallest Integer) Write a program that uses a for statement to find the smallestof several integers. Assume that the first value read specifies the number of values remaining.

ANS:

12 // 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 main

Enter the number of values to be summed followed by the values:5 100 200 300 400 500Sum of the 5 values is 1500

1 // Exercise 5.8 Solution: ex05_08.cpp2 // Find the smallest of several integers.3 #include <iostream>4 using namespace std;56 int main()7 {8 int number; // number of values9 int value; // current value

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

Page 4: Chapter 5

4 Chapter 5 Control Statements, Part 2: Solutions

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 resultsin 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 largenumber that it would not fit in an int or long variable.

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 onlyvalid values. For each number that is read, your program should print a line containing that numberof adjacent asterisks. For example, if your program reads the number 7, it should print *******.

Enter the number of integers to be processed followed by the integers:6 10 3 15 21 26 14

The smallest integer is: 3

1 // Exercise 5.10 Solution: ex05_10.cpp2 // Factorial program.3 #include <iostream>4 using namespace std;56 int main()7 {8 int factorial = 1; // current factorial value9

10 // display table headers11 cout << "x\tx!\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 main

x x!1 12 23 64 245 120

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 5: Chapter 5

Student Solution Exercises 5

ANS:

5.15 (GradeBook Modification) Modify the GradeBook program of Fig. 5.9–Fig. 5.11 to calculatethe grade-point average. A grade of A is worth 4 points, B is worth 3 points, and so on.

ANS:

1 // Exercise 5.13 Solution: ex05_13.cpp2 // Displaying bar charts using asterisks.3 #include <iostream>4 using namespace std;56 int main()7 {8 int number; // current number9

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

Enter 5 numbers between 1 and 30: 16 12 8 27 9************************************************************************

1 // Exercise 5.15 Solution: GradeBook.h2 // Definition of class GradeBook that counts A, B, C, D and F grades.3 // Member functions are defined in GradeBook.cpp4 #include <string> // program uses C++ standard string class5 using namespace std;67 // GradeBook class definition8 class GradeBook9 {

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.

Page 6: Chapter 5

6 Chapter 5 Control Statements, Part 2: Solutions

14 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.cpp2 // Member-function definitions for class GradeBook that3 // uses a switch statement to count A, B, C, D and F grades.4 #include <iostream>5 #include <iomanip> // parameterized stream manipulators6 #include "GradeBook.h"7 using namespace std;89 // 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.

Page 7: Chapter 5

Student Solution Exercises 7

42 {43 // this statement calls getCourseName to get the44 // name of the course this GradeBook represents45 cout << "Welcome to the grade book for\n" << 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.

Page 8: Chapter 5

8 Chapter 5 Control Statements, Part 2: Solutions

96 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 << "\n\nNumber 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.cpp2 // Create GradeBook object, input grades and display grade report.34 // include definition of class GradeBook from GradeBook.h5 #include "GradeBook.h"67 int main()8 {9 // create GradeBook object myGradeBook and

10 // 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.

Page 9: Chapter 5

Student Solution Exercises 9

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

Welcome 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^Z

Number of students who received each letter grade:A: 4B: 0C: 1D: 0F: 1

The class average is: 3.0

1 // Exercise 5.18 Solution: ex05_18.cpp2 // Display decimal, binary, octal and hexadecimal numbers.3 #include <iostream>4 using namespace std;56 int main()7 {8 int number; // loop counter for binary numbers9 int factor; // current factor for binary numbers

1011 // use tabs to display table headers12 cout << "Decimal\t\tBinary\t\tOctal\tHexadecimal\n";1314 // loop from 1 to 25615 for ( int loop = 1; loop <= 256; loop++ )16 {17 cout << dec << loop << "\t\t";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.

Page 10: Chapter 5

10 Chapter 5 Control Statements, Part 2: Solutions

5.21 (Calculating Salaries) A company pays its employees as managers (who receive a fixed weeklysalary), 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 fixedamount of money per item for each of the items they produce—each pieceworker in this companyworks on only one type of item). Write a program to compute the weekly pay for each employee. Youdo 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 havecode 4. Use a switch to compute each employee’s pay according to that employee’s paycode. Within

2324 // 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 main

Decimal 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

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 11: Chapter 5

Student Solution Exercises 11

the switch, prompt the user (i.e., the payroll clerk) to enter the appropriate facts your program needsto calculate each employee’s pay according to that employee’s paycode.

ANS:

1 // Exercise 5.21 Solution: ex05_21.cpp2 // Calculate wages for each employee.3 #include <iostream>4 #include <iomanip> // parameterized stream manipulators5 using namespace std;67 int main()8 {9 int payCode; // current employee's pay code

10 int pieces; // current pieceworker's number of pieces11 double salary; // current employee's salary12 double hours; // current hourly employee's hours13 double pay; // current employee's 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 // manager's pay is weekly salary34 cout << "The manager's 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.

Page 12: Chapter 5

12 Chapter 5 Control Statements, Part 2: Solutions

5152 // display current employee's pay53 cout << "Worker's 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 employee's pay66 cout << "Commission worker's 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 employee's pay82 cout << "Pieceworker's 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.

Page 13: Chapter 5

Student Solution Exercises 13

5.23 (Diamond of Asterisks) Write a program that prints the following diamond shape. You mayuse output statements that print a single asterisk (*), a single blank or a single newline. Maximizeyour use of repetition (with nested for statements) and minimize the number of output statements.

ANS:

Enter paycode (-1 to end): 1Manager selected.Enter weekly salary: 1200The manager's pay is $ 1200.00

Enter paycode (-1 to end): 2Hourly worker selected.Enter the hourly salary: 9.50Enter the total hours worked: 20Worker's pay is $ 190.00

Enter paycode (-1 to end): 3Commission worker selected.Enter gross weekly sales: 4000Commission worker's pay is $ 478.00

Enter paycode (-1 to end): 4Pieceworker selected.Enter number of pieces: 50Enter wage per piece: 3Pieceworker's pay is $ 150.00

Enter paycode (-1 to end): -1

****

************

*************************

1 // Exercise 5.23 Solution: ex05_23.cpp2 // Drawing a diamond shape with asterisks using nested control statements.3 #include <iostream>4 using namespace std;56 int main()7 {8 // top half9 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.

Page 14: Chapter 5

14 Chapter 5 Control Statements, Part 2: Solutions

5.26 What does the following program segment do?

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

*********

********************************

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 << '*';78 cout << endl;9 } // end inner for

1011 cout << endl;12 } // end outer for

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 15: Chapter 5

Student Solution Exercises 15

ANS:

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 thatappears in the body of the loop after the continue statement to an if statement thattests for the opposite of the continue condition. Thus, the code that was originallyafter the continue statement executes only when the if statement’s conditional ex-

1 // Exercise 5.26 Solution: ex05_26.cpp2 // Prints 5 groups of 3 lines, each containing 4 asterisks.3 #include <iostream>4 using namespace std;56 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

************

************

************

************

************

© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Page 16: Chapter 5

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 thenext iteration of the loop by not executing the remaining code in the loop’s body.

1 // Exercise 5.27 Solution: ex05_27.cpp2 // Structured equivalent for continue statement.3 #include <iostream>4 using namespace std;56 int main()7 {8 for ( int count = 1; count <= 10; count++ ) // loop 10 times9 {

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 main

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