Exercises

  1. 4.11 (Correct the Code Errors) Identify and correct the error(s) in each of the following:

    1.  

      
      if (age >= 65); {
         cout << "Age is greater than or equal to 65" << endl;
      }
      else {
         cout << "Age is less than 65 << endl";
      }
      
    2.  

      
      if (age >= 65) {
         cout << "Age is greater than or equal to 65" << endl; 
      else; {
         cout << "Age is less than 65 << endl";
      }
      
    3.  

      
      unsigned int x{1};
      unsigned int total;
      
      while (x <= 10) {
         total += x;
         ++x;
      }
      
    4.  

      While (x <= 100)
         total += x;
         ++x;
      
    5. 
      while (y > 0) {
         cout << y << endl;
         ++y;
      }
      
  2. 4.12 (What Does this Program Do?) What does the following program print?

    
     1   // Exercise 4.12: Mystery.cpp
     2   #include <iostream>
     3   using namespace std;
     4
     5   int main() {
     6      unsigned int x{1};
     7      unsigned int total{0};
     8
     9      while (x <= 10) {
    10         int y = x * x;
    11         cout << y << endl;
    12         total += y;
    13         ++x;
    14      }
    15
    16      cout << "Total is " << total << endl;
    17   }
    

    For Exercises 4.134.16, perform each of these steps:

    1. Read the problem statement.

    2. Formulate the algorithm using pseudocode and top-down, stepwise refinement.

    3. Write a C++ program.

    4. Test, debug and execute the C++ program.

  3. 4.13 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several trips by recording miles driven and gallons used for each trip. Develop a C++ program that uses a while statement to input the miles driven and gallons used for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all tankfuls up to this point.

    
    Enter miles driven (-1 to quit): 287
    Enter gallons used: 13
    MPG this trip: 22.076923
    Total MPG: 22.076923
    
    Enter miles driven (-1 to quit): 200
    Enter gallons used: 10
    MPG this trip: 20.000000
    Total MPG: 21.173913
    
    Enter the miles driven (-1 to quit): 120
    Enter gallons used: 5
    MPG this trip: 24.000000
    Total MPG: 21.678571
    
    Enter the miles used (-1 to quit): -1
    
  4. 4.14 (Credit Limits) Develop a C++ program that will determine whether a department-store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available:

    1. Account number (an integer)

    2. Balance at the beginning of the month

    3. Total of all items charged by this customer this month

    4. Total of all credits applied to this customer's account this month

    5. Allowed credit limit

    The program should use a while statement to input each of these facts, calculate the new balance (= beginning balance + charges – credits) and determine whether the new balance exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the program should display the customer’s account number, credit limit, new balance and the message “Credit Limit Exceeded.”

    
    Enter account number (or -1 to quit): 100
    Enter beginning balance: 5394.78
    Enter total charges: 1000.00
    Enter total credits: 500.00
    Enter credit limit: 5500.00
    New balance is 5894.78
    Account:      100
    Credit limit: 5500.00
    Balance:      5894.78
    Credit Limit Exceeded.
    
    Enter Account Number (or -1 to quit): 200
    Enter beginning balance: 1000.00
    Enter total charges: 123.45
    Enter total credits: 321.00
    Enter credit limit: 1500.00
    New balance is 802.45
    
    Enter Account Number (or -1 to quit): -1
    
  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 a total of $650. Develop a C++ program that uses a while statement to input each salesperson’s gross sales for last week and calculates and displays that salesperson’s earnings. Process one salesperson’s figures at a time.

    
    Enter sales in dollars (-1 to end): 5000.00
    Salary is: $650.00
    
    Enter sales in dollars (-1 to end): 6000.00
    Salary is: $740.00
    
    Enter sales in dollars (-1 to end): 7000.00
    Salary is: $830.00
    
    Enter sales in dollars (-1 to end): -1
    
  6. 4.16 (Salary Calculator) Develop a C++ program that uses a while statement to determine the gross pay for each of several employees. The company pays “straight time” for the first 40 hours worked by each employee and pays “time-and-a-half” for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee and should determine and display the employee’s gross pay.

    
    Enter hours worked (-1 to end): 39
    Enter hourly rate of the employee ($00.00): 10.00
    Salary is $390.00
    
    Enter hours worked (-1 to end): 40
    Enter hourly rate of the employee ($00.00): 10.00
    Salary is $400.00
    
    Enter hours worked (-1 to end): 41
    Enter hourly rate of the employee ($00.00): 10.00
    Salary is $415.00
    
    Enter hours worked (-1 to end): -1
    
  7. 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 determine and print the largest of 10 numbers input by the user. Your program should use three variables, as follows:

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

    2. number—The current number input to the program.

    3. largest—The largest number found so far.

  8. 4.18 (Tabular Output) Write a C++ program that uses a while statement and the tab escape sequence to print the following table of values:

    
    N       10*N    100*N   1000*N
    1       10      100     1000
    2       20      200     2000
    3       30      300     3000
    4       40      400     4000
    5       50      500     5000
    
  9. 4.19 (Find the Two Largest Numbers) Using an approach similar to that in Exercise 4.17, find the two largest values among the 10 numbers. [Note: You must input each number only once.]

  10. 4.20 (Validating User Input) The examination-results program of Fig. 4.14 assumes that any value input by the user that’s 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.

  11. 4.21 (What Does this Program Do?) What does the following program print?

    
     1   // Exercise 4.21: Mystery2.cpp
     2   #include <iostream>
     3   using namespace std;
     4
     5   int main() {
     6      unsigned int count{1};
     7
     8      while (count <= 10) {
     9         cout << (count % 2 == 1 ? "****" : "++++++++") << endl;
    10         ++count;
    11      }
    12   }
    
  12. 4.22 (What Does this Program Do?) What does the following program print?

    
     1   // Exercise 4.22: Mystery3.cpp
     2   #include <iostream>
     3   using namespace std;
     4
     5   int main() {
     6      unsigned int row{10};
     7
     8      while (row >= 1) {
     9         unsigned int column{1};
    10
    11         while (column <= 10) {
    12            cout << (row % 2 == 1 ? "<" : ">");
    13            ++column;
    14         }
    15
    16         --row;
    17         cout << endl;
    18      }
    19   }
    
  13. 4.23 (Dangling-else Problem) C++ compilers always associate an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what is referred to as the dangling-else problem. The indentation of the nested statement

    
    if (x > 5)
       if (y > 5)
          cout << "x and y are > 5";
       else
          cout << "x is <= 5";
    

    appears to indicate that if x is greater than 5, the nested if statement determines whether y is also greater than 5. If so, the statement outputs the string "x and y are > 5". Otherwise, it appears that if x is not greater than 5, the else part of the ifelse outputs the string "x is <= 5". Beware! This nested ifelse statement does not execute as it appears. The compiler actually interprets the statement as

    
    if (x > 5)
       if (y > 5)
          cout << "x and y are > 5";
       else
          cout << "x is <= 5";
    

    in which the body of the first if is a nested ifelse. The outer if statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5. Equally bad, if the outer if statement’s condition is false, the inner ifelse is skipped and nothing is displayed. For this exercise, add braces to the preceding code snippet to force the nested ifelse statement to execute as it was originally intended.

  14. 4.24 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 4.23, state the output for each of the following code snippets when x is 9 and y is 11 and when x is 11 and y is 9. We eliminated the indentation from the following code to make the problem more challenging. [Hint: Apply indentation conventions you’ve learned.]

    1. 
      if (x < 10)
      if (y > 10)
      cout << "*****" << endl;
      else
      cout << "#####" << endl;
      cout << "$$$$$" << endl;
      
    2.  

      
      if (x < 10)
      {
      if (y > 10)
      cout << "*****" << endl;
      }
      else
      {
      cout << "#####" << endl;
      cout << "$$$$$" << endl;
      }
      
  15. 4.25 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 4.23, modify the following code to produce the output shown. Use proper indentation techniques. You must not make any additional changes other than inserting braces. We eliminated the indentation from the following code to make the problem more challenging. [Note: It’s possible that no modification is necessary.]

    
    if ( y == 8 )
    if ( x == 5 )
    cout << "@@@@@" << endl;
    else
    cout << "#####" << endl;
    cout << "$$$$$" << endl;
    cout << "&&&&&" << endl;
    
    1. Assuming x = 5 and y = 8, the following output is produced.

      
      @@@@@
      $$$$$
      &&&&&
      
    2. Assuming x = 5 and y = 8, the following output is produced.

      
      @@@@@
      
    3. Assuming x = 5 and y = 8, the following output is produced.

      
      @@@@@
      &&&&&
      
    4. Assuming x = 5 and y = 7, the following output is produced. [Note: The last three output statements after the else are all part of a block.]

      
      #####
      $$$$$
      &&&&&
      
  16. 4.26 (Square of Asterisks) Write a program that reads in the size of the side of a square, then prints a hollow square of that size out of asterisks and blanks. Your program should work for squares of all side sizes between 1 and 20. For example, if your program reads a size of 5, it should print

    
    *****
    *   *
    *   *
    *   *
    *****
    
  17. 4.27 (Palindromes) A palindrome is a number or a text phrase that reads the same backward as forward. 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 remainder operators to separate the number into its individual digits.]

  18. 4.28 (Printing the Decimal Equivalent of a Binary Number) Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent. Use the remainder and division operators to pick off the “binary” number’s digits one at a time from right to left. Much as in the decimal number system, where the rightmost digit has a positional value of 1, the next digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as 2 * 100 + 3 * 10 + 4 * 1. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8, or 13. [Note: To learn more about binary numbers, refer to Appendix D.]

  19. 4.29 (Checkerboard Pattern of Asterisks) Write a program that displays the following checkerboard pattern. Your program must use only three output statements, one of each of the following forms:

    
    cout << "* ";
    cout << ' ';
    cout << endl;
    
    
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    
  20. 4.30 (Multiples of 2 with an Infinite Loop) Write a program that prints the powers of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your while loop should not terminate (i.e., you should create an infinite loop). To do this, simply use the keyword true as the expression for the while statement. What happens when you run this program?

  21. 4.31 (Calculating a Circle’s Diameter, Circumference and Area) Write a program that reads the radius of a circle (as a double value) and computes and prints the diameter, the circumference and the area. Use the value 3.14159 for π.

  22. 4.32 What’s wrong with the following statement? Provide the correct statement to accomplish what the programmer was probably trying to do.

    
    cout << ++( x + y );
    
  23. 4.33 (Sides of a Triangle) Write a program that reads three nonzero double values and determines and prints whether they could represent the sides of a triangle.

  24. 4.34 (Sides of a Right Triangle) Write a program that reads three nonzero integers and determines and prints whether they’re the sides of a right triangle.

  25. 4.35 (Factorial) The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is defined as follows:

    andn!=n(n1)(n2)...1(for values of n greater than 1)n!=1(for n=0 or n=1).

    For example, 5!=54321, which is 120. Use while statements in each of the following:

    1. Write a program that reads a nonnegative integer and computes and prints its factorial.

    2. Write a program that estimates the value of the mathematical constant e by using the formula:

      e=1+11!+12!+13!+...

      Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).

    3. Write a program that computes the value of ex by using the formula

      ex=1+x1!+x22!+x33!+...

      Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).

  26. 4.36 (Modified Account Class) Modify class Account (Exercise 3.9) to represent the balance data member as type double. Also, display all double amounts with two digits to the right of the decimal point.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset