chapter 4

14
4 Control Statements, Part 1: Solutions 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 ifelse 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.

Upload: hani-sweileh

Post on 22-May-2015

412 views

Category:

Technology


2 download

DESCRIPTION

C++ - 7 edition - Solution Manual

TRANSCRIPT

Page 1: Chapter 4

4Control Statements, Part 1:Solutions

Let’s all move one place on.—Lewis Carroll

The wheel is come full circle.—William Shakespeare

How many apples fell onNewton’s head before he took thehint!—Robert Frost

All the evolution we know ofproceeds from the vague to thedefinite.—Charles Sanders Peirce

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

■ Basic problem-solvingtechniques.

■ To develop algorithmsthrough the process of top-down, stepwise refinement.

■ To use the if and if…else

selection statements tochoose among alternativeactions.

■ To use the while repetitionstatement to executestatements in a programrepeatedly.

■ Counter-controlled repetitionand sentinel-controlledrepetition.

■ To use the increment,decrement and assignmentoperators.

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

Page 2: Chapter 4

2 Chapter 4 Control Statements, Part 1: Solutions

Student 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 doublequote 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 thesecond 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.

Page 3: Chapter 4

Student Solution Exercises 3

ANS:

Top:

Determine the current and combined miles/gallon for each tank of gas

First refinement:

Initialize variablesFor each tank of gas, input the miles driven and gallons used, then calculate and printthe miles/gallon for that tank of gasCalculate and print the overall average miles/gallon

Second refinement:

Initialize totalGallons to zeroInitialize totalMiles to zero

Prompt the user to enter the miles used for the first tankInput the miles used for the first tank (possibly the sentinel)

While the sentinel value (-1) has not been entered for the milesPrompt the user to enter the gallons used for the current tankInput the gallons used for the current tank

Add miles to the running total in totalMilesAdd gallons to the running total in totalGallons

If gallons is not zeroCalculate and print the miles/gallon

If totalGallons is not zeroCalculate and print the totalMiles/totalGallons

Prompt the user for the next tank’s number of milesInput the miles used for the next tank

Enter miles driven (-1 to quit): 287Enter gallons used: 13MPG this tankful: 22.076923Total MPG: 22.076923

Enter miles driven (-1 to quit): 200Enter gallons used: 10MPG this tankful: 20.000000Total MPG: 21.173913

Enter the miles driven (-1 to quit): 120Enter gallons used: 5MPG this tankful: 24.000000Total MPG: 21.678571

Enter the miles used (-1 to quit): -1

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

Page 4: Chapter 4

4 Chapter 4 Control Statements, Part 1: Solutions

56 int main()7 {8 double gallons; // gallons used for current tank9 double miles; // miles driven for current tank

10 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 << "\n\nEnter miles driven (-1 to quit): ";49 cin >> miles;50 } // end while51 } // end main

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

Page 5: Chapter 4

Student Solution Exercises 5

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

ANS:

Top:

For an arbitrary number of salespeople, determine each salesperson’s earnings for theprevious week

First refinement:

For each salespersonInput the salesperson’s sales for the weekCalculate and print the salesperson’s wages for the week

Second refinement:

Prompt the user for the first salesperson’s sales in dollarsInput the first salesperson’s sales in dollars

While the sentinel value (-1) has not been entered for the salesCalculate 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)

Enter miles driven (-1 to quit): 287Enter gallons used: 13MPG this tankful: 22.076923Total MPG: 22.076923

Enter miles driven (-1 to quit): 200Enter gallons used: 10MPG this tankful: 20.000000Total MPG: 21.173913

Enter miles driven (-1 to quit): 120Enter gallons used: 5MPG this tankful: 24.000000Total MPG: 21.678571

Enter miles driven (-1 to quit): -1

Enter sales in dollars (-1 to end): 5000.00Salary is: $650.00

Enter sales in dollars (-1 to end): 6000.00Salary is: $740.00

Enter sales in dollars (-1 to end): 7000.00Salary is: $830.00

Enter sales in dollars (-1 to end): -1

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

Page 6: Chapter 4

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 dollarsInput the next salesperson’s sales in dollars

4.17 (Find the Largest) The process of finding the largest number (i.e., the maximum of a groupof numbers) is used frequently in computer applications. For example, a program that determinesthe winner of a sales contest inputs the number of units sold by each salesperson. The salespersonwho 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 usethree variables, as follows:

1 // Exercise 4.15 Solution: ex04_15.cpp2 // Calculate salesperson earnings.3 #include <iostream>4 #include <iomanip> // parameterized stream manipulators5 using namespace std;67 int main()8 {9 double sales; // gross weekly sales

10 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 << "\n\nEnter sales in dollars (-1 to end): ";28 cin >> sales;29 } // end while30 } // end main

Enter sales in dollars (-1 to end): 5000.00Salary is: $650.00

Enter sales in dollars (-1 to end): 6000.00Salary is: $740.00

Enter sales in dollars (-1 to end): 7000.00Salary is: $830.00

Enter sales in dollars (-1 to end): -1

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

Page 7: Chapter 4

Student Solution Exercises 7

counter: A counter to count to 10 (i.e., to keep track of how many numbers havebeen 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:

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. Onany input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value.

1 // Exercise 4.17 Solution: ex04_17.cpp2 // Finding the largest number.3 #include <iostream>4 #include <iomanip> // parameterized stream manipulators5 using namespace std;67 int main()8 {9 int counter = 0; // counter for 10 repetitions

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

Enter 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

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

Page 8: Chapter 4

8 Chapter 4 Control Statements, Part 1: Solutions

ANS:

1 // Exercise 4.20 Solution: ex04_20.cpp2 // Examination results problem: Validating input.3 #include <iostream>4 using namespace std;56 int main()7 {8 // initializing variables in declarations9 int passes = 0; // number of passes

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

Page 9: Chapter 4

Student Solution Exercises 9

4.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:

Enter 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 3

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.

Page 10: Chapter 4

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.

Page 11: Chapter 4

Student Solution Exercises 11

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 and11611. 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:

63 cout << "$$$$$" << endl;64 } // end else65 } // end main

Output 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:#####$$$$$

1 // Exercise 4.26 Solution: ex04_26.cpp2 // Determine whether a number is a palindrome.3 #include <iostream>4 using namespace std;56 int main()7 {8 int number = 0; // user input number9 int digit1; // first digit

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

Page 12: Chapter 4

12 Chapter 4 Control Statements, Part 1: Solutions

4.28 (Checkerboard Pattern of Asterisks) Write a program that displays the checkerboard patternshown below. Your program must use only three output statements, one of each of the followingforms:

cout << "* ";cout << ' ';cout << endl;

ANS:

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

Enter a 5-digit number: 1232112321 is a palindrome!!!

Enter a 5-digit number: 1234512345 is not a palindrome.

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

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

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

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

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.

Page 13: Chapter 4

Student Solution Exercises 13

4.30 Write a program that reads the radius of a circle (as a double value) and computes and printsthe diameter, the circumference and the area. Use the value 3.14159 for π.

ANS:

4 using namespace std;56 int main()7 {8 int row = 8; // row counter9 int side; // side counter

1011 while ( row-- > 0 ) // loop 8 times12 {13 side = 8; // reset side counter1415 // if even row, begin with a space16 if ( row % 2 == 0 )17 cout << ' ';1819 while ( side-- > 0 ) // loop 8 times20 cout << "* ";2122 cout << endl; // go to next line23 } // end while24 } // end main

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

1 // Exercise 4.30 Solution: ex04_30.cpp2 // Calculate the diameter, circumference and area of a cirle.3 #include <iostream>4 using namespace std;56 int main()7 {8 double radius; // input radius9 double pi = 3.14159; // value for pi

1011 // get radius value12 cout << "Enter the radius: ";13 cin >> radius;1415 // compute and display diameter16 cout << "The diameter is " << radius * 2.0;17

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

Page 14: Chapter 4

14 Chapter 4 Control Statements, Part 1: Solutions

18 // compute and display circumference19 cout << "\nThe circumference is " << 2.0 * pi * radius;2021 // compute and display area22 cout << "\nThe area is " << pi * radius * radius << endl;23 } // end main

Enter the radius: 25The diameter is 50The circumference is 157.08The area is 1963.49

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