Upcoming SlideShare
×

# Chapter 4

1,451 views

Published on

C++ - 7 edition - Solution Manual

Published in: Technology
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

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

• Be the first to like this

Views
Total views
1,451
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
63
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Chapter 4

1. 1. Control Statements, Part 1:Solutions 4 Let’s all move one place on. —Lewis Carroll The wheel is come full circle. —William Shakespeare How many apples fell on Newton’s head before he took the hint! —Robert Frost All the evolution we know of proceeds from the vague to the definite. —Charles Sanders Peirce Objectives In this chapter you’ll learn: ■ Basic problem-solving techniques. ■ To develop algorithms through the process of top- down, stepwise refinement. ■ To use the if and if…else selection statements to choose among alternative actions. ■ To use the while repetition statement to execute statements in a program repeatedly. ■ Counter-controlled repetition and sentinel-controlled repetition. ■ To use the increment, decrement and assignment operators. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
2. 2. 2 Chapter 4 Control Statements, Part 1: SolutionsStudent Solution Exercises4.11 Identify and correct the error(s) in each of the following: a) if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl"; ANS: The semicolon at the end of the if condition should be removed. The closing double quote after the second endl should be placed after 65. b) if ( age >= 65 ) cout << "Age is greater than or equal to 65" << endl; else; cout << "Age is less than 65 << endl"; ANS: The semicolon after the else should be removed. The closing double quote after the second endl should be placed after 65. c) int x = 1, total; while ( x <= 10 ) { total += x; ++x; } ANS: Variable total should be initialized to 0. d) While ( x <= 100 ) total += x; ++x; ANS: The W in while should be lowercase. The while’s body should be enclosed in braces {}. e) while ( y > 0 ) { cout << y << endl; ++y; } ANS: The variable y should be decremented (i.e., y--;), not incremented ( y++;).For Exercise 4.13 and Exercise 4.15, perform each of these steps: a) Read the problem statement. b) Formulate the algorithm using pseudocode and top-down, stepwise refinement. c) Write a C++ program. d) Test, debug and execute the C++ program.4.13 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles. Onedriver has kept track of several tankfuls of gasoline by recording miles driven and gallons used foreach tankful. Develop a C++ program that uses a while statement to input the miles driven and gal-lons used for each tankful. The program should calculate and display the miles per gallon obtainedfor each tankful and print the combined miles per gallon obtained for all tankfuls up to this point. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
3. 3. Student Solution Exercises 3Enter miles driven (-1 to quit): 287Enter gallons used: 13MPG this tankful: 22.076923Total MPG: 22.076923Enter miles driven (-1 to quit): 200Enter gallons used: 10MPG this tankful: 20.000000Total MPG: 21.173913Enter the miles driven (-1 to quit): 120Enter gallons used: 5MPG this tankful: 24.000000Total MPG: 21.678571Enter the miles used (-1 to quit): -1 ANS: Top: Determine the current and combined miles/gallon for each tank of gas First refinement: Initialize variables For each tank of gas, input the miles driven and gallons used, then calculate and print the miles/gallon for that tank of gas Calculate and print the overall average miles/gallon Second refinement: Initialize totalGallons to zero Initialize totalMiles to zero Prompt the user to enter the miles used for the first tank Input the miles used for the first tank (possibly the sentinel) While the sentinel value (-1) has not been entered for the miles Prompt the user to enter the gallons used for the current tank Input the gallons used for the current tank Add miles to the running total in totalMiles Add gallons to the running total in totalGallons If gallons is not zero Calculate and print the miles/gallon If totalGallons is not zero Calculate and print the totalMiles/totalGallons Prompt the user for the next tank’s number of miles Input the miles used for the next tank1 // Exercise 4.13 Solution: ex04_13.cpp2 // Calculate average MPG with sentinel-controlled repetition.3 #include <iostream>4 using namespace std; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
4. 4. 4 Chapter 4 Control Statements, Part 1: Solutions 5 6 int main() 7 { 8 double gallons; // gallons used for current tank 9 double miles; // miles driven for current tank10 double totalGallons = 0; // total gallons used11 double totalMiles = 0; // total miles driven1213 double milesPerGallon; // miles per gallon for tankful14 double totalMilesPerGallon; // miles per gallon for trip1516 // processing phase17 // get miles used for first tank18 cout << "Enter miles driven (-1 to quit): ";19 cin >> miles;20 cout << fixed; // set floating-point number format2122 // exit if the input is -1; otherwise, proceed with the program23 while ( miles != -1 )24 {25 // prompt user for gallons and obtain the input from user26 cout << "Enter gallons used: ";27 cin >> gallons;2829 // add gallons and miles for this tank to total30 totalMiles += miles;31 totalGallons += gallons;3233 // calculate miles per gallon for the current tank34 if ( gallons != 0 )35 {36 milesPerGallon = miles / gallons;37 cout << "MPG this tankful: " << milesPerGallon;38 } // end if3940 // calculate miles per gallon for the total trip41 if ( totalGallons != 0 )42 {43 totalMilesPerGallon = totalMiles / totalGallons;44 cout << "nTotal MPG: " << totalMilesPerGallon;45 } // end if4647 // prompt user for new value for miles48 cout << "nnEnter miles driven (-1 to quit): ";49 cin >> miles;50 } // end while51 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
5. 5. Student Solution Exercises 5Enter miles driven (-1 to quit): 287Enter gallons used: 13MPG this tankful: 22.076923Total MPG: 22.076923Enter miles driven (-1 to quit): 200Enter gallons used: 10MPG this tankful: 20.000000Total MPG: 21.173913Enter miles driven (-1 to quit): 120Enter gallons used: 5MPG this tankful: 24.000000Total MPG: 21.678571Enter miles driven (-1 to quit): -14.15 (Sales Commission Calculator) A large company pays its salespeople on a commission basis.The salespeople each receive \$200 per week plus 9% of their gross sales for that week. For example,a salesperson who sells \$5000 worth of chemicals in a week receives \$200 plus 9% of \$5000, or atotal of \$650. Develop a C++ program that uses a while statement to input each salesperson’s grosssales for last week and calculates and displays that salesperson’s earnings. Process one salesperson’sfigures at a time.Enter sales in dollars (-1 to end): 5000.00Salary is: \$650.00Enter sales in dollars (-1 to end): 6000.00Salary is: \$740.00Enter sales in dollars (-1 to end): 7000.00Salary is: \$830.00Enter sales in dollars (-1 to end): -1 ANS: Top: For an arbitrary number of salespeople, determine each salesperson’s earnings for the previous week First refinement: For each salesperson Input the salesperson’s sales for the week Calculate and print the salesperson’s wages for the week Second refinement: Prompt the user for the first salesperson’s sales in dollars Input the first salesperson’s sales in dollars While the sentinel value (-1) has not been entered for the sales Calculate the salesperson’s wages for the week as 200 dollars added to 9 percent of the salesperson’s sales (calculated by multiplying the sales with .09) © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
6. 6. 6 Chapter 4 Control Statements, Part 1: Solutions Print the salesperson’s wages for the week Prompt the user for the next salesperson’s sales in dollars Input the next salesperson’s sales in dollars 1 // Exercise 4.15 Solution: ex04_15.cpp 2 // Calculate salesperson earnings. 3 #include <iostream> 4 #include <iomanip> // parameterized stream manipulators 5 using namespace std; 6 7 int main() 8 { 9 double sales; // gross weekly sales10 double wage; // commissioned earnings1112 // processing phase13 // get first sales14 cout << "Enter sales in dollars (-1 to end): ";15 cin >> sales;1617 // set floating-point number format18 cout << fixed << setprecision( 2 );1920 // loop until sentinel value read from user21 while ( sales != -1.0 )22 {23 wage = 200.0 + 0.09 * sales; // calculate wage24 cout << "Salary is: \$" << wage; // display salary2526 // prompt for next sales27 cout << "nnEnter sales in dollars (-1 to end): ";28 cin >> sales;29 } // end while30 } // end mainEnter sales in dollars (-1 to end): 5000.00Salary is: \$650.00Enter sales in dollars (-1 to end): 6000.00Salary is: \$740.00Enter sales in dollars (-1 to end): 7000.00Salary is: \$830.00Enter sales in dollars (-1 to end): -1 4.17 (Find the Largest) The process of finding the largest number (i.e., the maximum of a group of numbers) is used frequently in computer applications. For example, a program that determines the winner of a sales contest inputs the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a C++ program that uses a while statement to de- termine and print the largest number of 10 numbers input by the user. Your program should use three variables, as follows: © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
7. 7. Student Solution Exercises 7 counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed). number: The current number input to the program. largest: The largest number found so far. ANS: 1 // Exercise 4.17 Solution: ex04_17.cpp 2 // Finding the largest number. 3 #include <iostream> 4 #include <iomanip> // parameterized stream manipulators 5 using namespace std; 6 7 int main() 8 { 9 int counter = 0; // counter for 10 repetitions10 int number; // current number input11 int largest; // largest number found so far1213 cout << "Enter the first number: "; // prompt for first number14 cin >> largest; // get first number1516 while ( ++counter < 10 ) // loop 10 times17 {18 cout << "Enter the next number : "; // prompt for next input19 cin >> number; // get next number2021 // if current number input is greater than largest number,22 // update largest23 if ( number > largest )24 largest = number;25 } // end while2627 cout << "Largest is " << largest << endl; // display largest number28 } // end mainEnter the first number: 12Enter the next number : 123Enter the next number : 56Enter the next number : 9Enter the next number : 30Enter the next number : 35Enter the next number : 28Enter the next number : 345Enter the next number : 47Enter the next number : 90Largest is 345 4.20 (Validating User Input) The examination-results program of Fig. 4.16 assumes that any val- ue input by the user that is not a 1 must be a 2. Modify the application to validate its inputs. On any input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value. © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
8. 8. 8 Chapter 4 Control Statements, Part 1: Solutions ANS: 1 // Exercise 4.20 Solution: ex04_20.cpp 2 // Examination results problem: Validating input. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 // initializing variables in declarations 9 int passes = 0; // number of passes10 int failures = 0; // number of failures11 int studentCounter = 1; // student counter12 int result; // one exam result (1 = pass, 2 = fail)1314 // process 10 students using counter-controlled loop15 while ( studentCounter <= 10 )16 {17 // prompt user for input and obtain value from user18 cout << "Enter result (1 = pass, 2 = fail): ";19 cin >> result; // input result2021 if ( result == 1 ) // 1 is a valid input22 {23 passes = passes + 1; // increment passes24 studentCounter = studentCounter + 1; // increment studentCounter25 } // end if26 else if ( result == 2 ) // 2 is a valid input27 {28 failures = failures + 1; // increment failures29 studentCounter = studentCounter + 1; // increment studentCounter30 } // end else if31 else // invalid input; tell user and prompt again32 {33 cout << "Invalid input" << endl;34 } // end else35 } // end while3637 // termination phase; display number of passes and failures38 cout << "Passed " << passes << "nFailed " << failures << endl;3940 // determine whether more than eight students passed41 if ( passes > 8 )42 cout << "Bonus to instructor!" << endl;43 } // end main © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
9. 9. Student Solution Exercises 9Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 3Invalid resultEnter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 4Invalid resultEnter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 0Invalid resultEnter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Passed 7Failed 34.23 (Dangling-else Problem) State the output for each of the following when x is 9 and y is 11and when x is 11 and y is 9. The compiler ignores the indentation in a C++ program. The C++ com-piler always associates an else with the previous if unless told to do otherwise by the placement ofbraces {}. On first glance, you may not be sure which if and else match, so this is referred to asthe “dangling-else” problem. We eliminated the indentation from the following code to make theproblem more challenging. [Hint: Apply indentation conventions you’ve learned.] a) if ( x < 10 ) if ( y > 10 ) cout << "*****" << endl; else cout << "#####" << endl; cout << "\$\$\$\$\$" << endl; b) if ( x < 10 ) { if ( y > 10 ) cout << "*****" << endl; } else { cout << "#####" << endl; cout << "\$\$\$\$\$" << endl; } ANS:1 // Exercise 4.23 Solution: ex04_23.cpp2 // Dangling-else problem.3 #include <iostream>4 using namespace std;56 int main()7 {8 // part A, x=9 and y=11 © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
10. 10. 10 Chapter 4 Control Statements, Part 1: Solutions 9 int x = 9;10 int y = 11;11 cout << "Output for part A, x=9 and y=11:" << endl;1213 if ( x < 10 )14 if ( y > 10 )15 cout << "*****" << endl;16 else17 cout << "#####" << endl;1819 cout << "\$\$\$\$\$" << endl;2021 // part A, x=11 and y=922 x = 11;23 y = 9;24 cout << endl << "Output for part A, x=11 and y=9:" << endl;2526 if ( x < 10 )27 if ( y > 10 )28 cout << "*****" << endl;29 else30 cout << "#####" << endl;3132 cout << "\$\$\$\$\$" << endl;3334 // part B, x=9 and y=1135 x = 9;36 y = 11;37 cout << endl << "Output for part B, x=9 and y=11:" << endl;3839 if ( x < 10 )40 {41 if ( y > 10 )42 cout << "*****" << endl;43 } // end outer if44 else45 {46 cout << "#####" << endl;47 cout << "\$\$\$\$\$" << endl;48 } // end else4950 // part B, x=11 and y=951 x = 11;52 y = 9;53 cout << endl << "Output for part B, x=11 and y=9:" << endl;5455 if ( x < 10 )56 {57 if ( y > 10 )58 cout << "*****" << endl;59 } // end outer if60 else61 {62 cout << "#####" << endl; © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
11. 11. Student Solution Exercises 1163 cout << "\$\$\$\$\$" << endl;64 } // end else65 } // end mainOutput for part A, x=9 and y=11:*****\$\$\$\$\$Output for part A, x=11 and y=9:\$\$\$\$\$Output for part B, x=9 and y=11:*****Output for part B, x=11 and y=9:#####\$\$\$\$\$ 4.26 (Palindromes) A palindrome is a number or a text phrase that reads the same backward as for- ward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and determines whether it’s a palindrome. [Hint: Use the division and modulus operators to separate the number into its individual digits.] ANS: 1 // Exercise 4.26 Solution: ex04_26.cpp 2 // Determine whether a number is a palindrome. 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 int number = 0; // user input number 9 int digit1; // first digit10 int digit2; // second digit11 int digit4; // fourth digit; don’t care about third digit12 int digit5; // fifth digit13 int digits = 0; // number of digits in input1415 // ask for a number until it is five digits16 while ( digits != 5 )17 {18 cout << "Enter a 5-digit number: "; // prompt for a number19 cin >> number; // get number2021 // verify if number has 5 digits22 if ( number < 100000 )23 {24 if ( number > 9999 )25 digits = 5;26 else27 cout << "Number must be 5 digits" << endl;28 } // end if © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
12. 12. 12 Chapter 4 Control Statements, Part 1: Solutions29 else30 cout << "Number must be 5 digits" << endl;31 } // end while3233 // get the digits34 digit1 = number / 10000;35 digit2 = number % 10000 / 1000;36 digit4 = number % 10000 % 1000 % 100 / 10;37 digit5 = number % 10000 % 1000 % 100 % 10;3839 // print whether the number is a palindrome40 if ( digit1 == digit5 )41 {42 if ( digit2 == digit4 )43 cout << number << " is a palindrome!!!" << endl;44 else45 cout << number << " is not a palindrome." << endl;46 }47 else48 cout << number << " is not a palindrome." << endl;49 } // end mainEnter a 5-digit number: 1232112321 is a palindrome!!!Enter a 5-digit number: 1234512345 is not a palindrome. 4.28 (Checkerboard Pattern of Asterisks) Write a program that displays the checkerboard pattern shown below. Your program must use only three output statements, one of each of the following forms: cout << "* "; cout << ; cout << endl;* * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * * ANS:1 // Exercise 4.28 Solution: ex04_28.cpp2 // Prints out an 8 x 8 checkerboard pattern.3 #include <iostream> © 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.