Wrap-Up

Answers to Self Review Exercises

5.1
  1. False. The default case is optional. If no default action is needed, then there is no need for a default case. Nevertheless, it is considered good software engineering to always provide a default case.
  2. False. The break statement is used to exit the switch statement. The break statement is not required when the default case is the last case. Nor will the break statement be required if having control proceed with the next case makes sense.
  3. False. When using the && operator, both of the relational expressions must be true for the entire expression to be true.
  4. True.

5.2
  1. sum = 0; for ( count = 1; count <= 99; count += 2 ) sum += count;
  2. cout << fixed << left << setprecision( 1 ) << setw( 15 ) << 333.546372 << setprecision( 2 ) << setw( 15 ) << 333.546372 << setprecision( 3 ) << setw( 15 ) << 333.546372 << endl;

    Output is:

    333.5 333.55 333.546

  3. cout << fixed << setprecision( 2 ) << setw( 10 ) << pow( 2.5, 3 ) << endl;

    Output is:

    15.63

  4. x = 1; while ( x <= 20 ) { cout << x; if ( x % 5 == 0 ) cout << endl; else cout << ' '; x++; }
  5. for ( x = 1; x <= 20; x++ ) { cout << x; if ( x % 5 == 0 ) cout << endl; else cout << ' '; }

    or

    for ( x = 1; x <= 20; x++ ) { if ( x % 5 == 0 ) cout << x << endl; else cout << x << ' '; }

5.3
  1. Error: The semicolon after the while header causes an infinite loop.

    Correction: Replace the semicolon by a {, or remove both the ; and the }.

  2. Error: Using a floating-point number to control a for repetition statement.

    Correction: Use an integer and perform the proper calculation in order to get the values you desire.

    for ( y = 1; y != 10; y++ ) cout << ( static_cast< double >( y ) / 10 ) << endl;

  3. Error: Missing break statement in the first case.

    Correction: Add a break statement at the end of the statements for the first case. Note that this is not an error if the programmer wants the statement of case 2: to execute every time the case 1: statement executes.

  4. Error: Improper relational operator used in the while repetition-continuation condition.

    Correction: Use <= rather than <, or change 10 to 11.

Exercises

5.4

Find the error(s) in each of the following:

  1. For ( x = 100, x >= 1, x++ ) cout << x << endl;
  2. 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; }

  3. The following code should output the odd integers from 19 to 1:

    for ( x = 19; x >= 1; x += 2 ) cout << x << endl;

  4. The following code should output the even integers from 2 to 100:

    counter = 2; do { cout << counter << endl; counter += 2; } While ( counter < 100 );

5.5

Write a program that uses a for statement to sum a sequence of integers. 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.

5.6

Write a program that uses a for statement to calculate and print the average of several integers. Assume the last value read is the sentinel 9999. A typical input sequence might be

10 8 11 7 9 9999  

indicating that the program should calculate the average of all the values preceding 9999.

5.7

What does the following program do?

1 // Exercise 5.7: ex05_07.cpp 2 // What does this program print? 3 #include 4 using std::cout; 5 using std::cin; 6 using std::endl; 7 8 int main() 9 { 10 int x; // declare x 11 int y; // declare y 12
13 // prompt user for input 14 cout << "Enter two integers in the range 1-20: "; 15 cin >> x >> y; // read values for x and y 16 17 for ( int i = 1; i <= y; i++ ) // count from 1 to y 18 { 19 for ( int j = 1; j <= x; j++ ) // count from 1 to x 20 cout << '@'; // output @ 21 22 cout << endl; // begin new line 23 } // end outer for 24 25 return 0; // indicate successful termination 26 } // end main
5.8

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 and that the first number is not one of the integers to compare.

5.9

Write a program that uses a for statement to calculate and print the product of the odd integers from 1 to 15.

5.10

The factorial function is used frequently in probability problems. Using the definition of factorial in Exercise 4.35, write a program 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?

5.11

Modify the compound interest program of Section 5.4 to repeat its steps for the interest rates 5 percent, 6 percent, 7 percent, 8 percent, 9 percent and 10 percent. Use a for statement to vary the interest rate.

5.12

Write a program that uses for statements to print the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form cout << '*'; (this causes the asterisks to print side by side). [Hint: The last two patterns require that each line begin with an appropriate number of blanks. Extra credit: Combine your code from the four separate problems into a single program that prints all four patterns side by side by making clever use of nested for loops.]

(a) (b) (c) (d) * ********** ********** * ** ********* ********* ** *** ******** ******** *** **** ******* ******* **** ***** ****** ****** ***** ****** ***** ***** ****** ******* **** **** ******* ******** *** *** ******** ********* ** ** ********* ********** * * **********

5.13

One interesting application of computers is the drawing of 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 *******.

 
5.14

A mail order house sells five different products whose retail prices are: product 1 $2.98, product 2$4.50, product 3$9.98, product 4$4.49 and product 5$6.87. Write a program that reads a series of pairs of numbers as follows:

  1. product number
  2. quantity sold

Your program should use a switch statement to determine the retail price for each product. Your program should calculate and display the total retail value of all products sold. Use a sentinel-controlled loop to determine when the program should stop looping and display the final results.

5.15

Modify the GradeBook program of Fig. 5.9Fig. 5.11 so that it calculates the grade-point average for the set of grades. A grade of A is worth 4 points, B is worth 3 points, etc.

5.16

Modify the program in Fig. 5.6 so it uses only integers to calculate the compound interest. [Hint: Treat all monetary amounts as integral numbers of pennies. Then "break" the result into its dollar portion and cents portion by using the division and modulus operations. Insert a period.]

5.17

Assume i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? Are the parentheses necessary in each case?

  1. cout << ( i == 1 ) << endl;
  2. cout << ( j == 3 ) << endl;
  3. cout << ( i >= 1 && j < 4 ) << endl;
  4. cout << ( m <= 99 && k < m ) << endl;
  5. cout << ( j >= i || k == m ) << endl;
  6. cout << ( k + m < j || 3 - j >= k ) << endl;
  7. cout << ( !m ) << endl;
  8. cout << ( !( j - m ) ) << endl;
  9. cout << ( !( k > m ) ) << endl;

5.18

Write a program that prints a table of the binary, octal and hexadecimal equivalents of the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix D, Number Systems, first.

5.19

Calculate the value of p from the infinite series

 

Print a table that shows the approximate value of p after each of the first 1,000 terms of this series.

5.20

(Pythagorean Triples) A right triangle can have sides that are all integers. A set of three integer values for the sides of a right triangle is called a Pythagorean triple. These three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Find all Pythagorean triples for side1, side2 and hypotenuse all no larger than 500. Use a triple-nested for loop that tries all possibilities. This is an example of brute force computing. You will learn in more advanced computer-science courses that there are many interesting problems for which there is no known algorithmic approach other than sheer brute force.

5.21

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 wagefor 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 produceeach 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: Managers 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 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.


5.22

(De Morgan's Laws) In this chapter, we discussed the logical operators &&, || and !. De Morgan's laws can sometimes make it more convenient for us to express a logical expression. These laws state that the expression !( condition1 && condition2 ) is logically equivalent to the expression !( condition1 || condition2 ). Also, the expression ! ( condition1 || condition2 ) is logically equivalent to the expression ( !condition1 && ! condition2 ) . Use De Morgan's laws to write equivalent expressions for each of the following, then write a program to show that the original expression and the new expression in each case are equivalent:

  1. !( x < 5 ) && !( y >= 7 )
  2. !( a == b ) || !( g != 5 )
  3. !( ( x <= 8 ) && ( y > 4 ) )
  4. !( ( i > 4 ) || ( j <= 6 ) )

5.23

Write a program that prints the following diamond shape. You may use output statements that print either a single asterisk (*) or a single blank. Maximize your use of repetition (with nested for statements) and minimize the number of output statements.

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

5.24

Modify the program you wrote in Exercise 5.23 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond, then display a diamond of the appropriate size.

5.25

A criticism of the break and continue statements is that each is unstructured. Actually they statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you would remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement leaves a loop from within the body of the loop. Another way to leave is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates "early exit because of a 'break' condition."] Use the technique you developed here to remove the break statement from the program of Fig. 5.13.

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 for 10 11 cout << endl; 12 } // end outer for

 
5.27

Describe in general how you would remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the technique you developed here to remove the continue statement from the program of Fig. 5.14.

5.28

("The Twelve Days of Christmas" Song) Write a program that uses repetition and switch statements to print the song "The Twelve Days of Christmas." One switch statement should be used to print the day (i.e., "First," "Second," etc.). A separate switch statement should be used to print the remainder of each verse. Visit the Web site www.12days.com/library/carols/12daysofxmas.htm for the complete lyrics to the song.

5.29

(Peter Minuit Problem) Legend has it that, in 1626, Peter Minuit purchased Manhattan Island for $24.00 in barter. Did he make a good investment? To answer this question, modify the compound interest program of Fig. 5.6 to begin with a principal of $24.00 and to calculate the amount of interest on deposit if that money had been kept on deposit until this year (e.g., 379 years through 2005). Place the for loop that performs the compound interest calculation in an outer for loop that varies the interest rate from 5 percent to 10 percent to observe the wonders of compound interest.

Категории