Exercises

  1. 6.11 Show the value of x after each of the following statements is performed:

    1. x = fabs(7.5);

    2. x = floor(7.5);

    3. x = fabs(0.0);

    4. x = ceil(0.0);

    5. x = fabs(-6.4);

    6. x = ceil(-6.4);

    7. x = ceil(-fabs(-8 + floor(-5.5)));

  2. 6.12 (Parking Charges) A parking garage charges a $20.00 minimum fee to park for up to three hours. The garage charges an additional $5.00 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $50.00. Assume that no car parks for longer than 24 hours at a time. Write a program that calculates and prints the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday’s receipts. The program should use the function calculateCharges to determine the charge for each customer. Your outputs should appear in the following format:

    
    Car      Hours        Charge
    1          1.5         20.00
    2          4.0         25.00
    3         24.0         50.00
    TOTAL     29.5         95.50
    
  3. 6.13 (Rounding Numbers) An application of function floor is rounding a value to the nearest integer. The statement

    
    y = floor(x + 0.5);
    

    rounds the number x to the nearest integer and assigns the result to y. Write a program that reads several numbers and uses the preceding statement to round each of these numbers to the nearest integer. For each number processed, print both the original number and the rounded number.

  4. 6.14 (Rounding Numbers) Function floor can be used to round a number to a specific decimal place. The statement

    
    y = floor(x * 10 + 0.5) / 10;
    

    rounds x to the tenths position (the first position to the right of the decimal point). The statement

    
    y = floor(x * 100 + 0.5) / 100;
    

    rounds x to the hundredths position (the second position to the right of the decimal point). Write a program that defines four functions to round a number x in various ways:

    1. roundToInteger(number)

    2. roundToTenths(number)

    3. roundToHundredths(number)

    4. roundToThousandths(number)

    For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.

  5. 6.15 (Short-Answer Questions) Answer each of the following questions:

    1. What does it mean to choose numbers “at random?”

    2. Why is the rand function useful for simulating games of chance?

    3. Why would you randomize a program by using srand? Under what circumstances is it desirable not to randomize?

    4. Why is it often necessary to scale or shift the values produced by rand?

    5. Why is computerized simulation of real-world situations a useful technique?

  6. 6.16 (Random Numbers) Write statements that assign random integers to the variable n in the following ranges:

    1. 1n2

    2. 1n100

    3. 0n9

    4. 1000n1112

    5. 1n1

    6. 3n11

  7. 6.17 (Random Numbers) Write a single statement that prints a number at random from each of the following sets:

    1. 2, 4, 6, 8, 10.

    2. 3, 5, 7, 9, 11.

    3. 6, 10, 14, 18, 22.

  8. 6.18 (Exponentiation) Write a function integerPower(base, exponent) that returns the value of baseexponent

    For example, integerPower(3, 4) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer and that base is an integer. Do not use any math library functions.

  9. 6.19 (Hypotenuse Calculations) Define a function hypotenuse that calculates the hypotenuse of a right triangle when the other two sides are given. The function should take two double arguments and return the hypotenuse as a double. Use this function in a program to determine the hypotenuse for each of the triangles shown below.

    Triangle Side 1 Side 2
    1 3.0 4.0
    2 5.0 12.0
    3 8.0 15.0
  10. 6.20 (Multiples) Write a function isMultiple that determines for a pair of integers whether the second is a multiple of the first. The function should take two integer arguments and return true if the second is a multiple of the first, false otherwise. Use this function in a program that inputs a series of pairs of integers.

  11. 6.21 (Even Numbers) Write a program that inputs a series of integers and passes them one at a time to function isEven, which uses the remainder operator to determine whether an integer is even. The function should take an integer argument and return true if the integer is even and false otherwise.

  12. 6.22 (Square of Asterisks) Write a function that displays at the left margin of the screen a solid square of asterisks whose side is specified in integer parameter side. For example, if side is 4, the function displays the following:

    
    ****
    ****
    ****
    ****
    
  13. 6.23 (Square of Any Character) Modify the function created in Exercise 6.22 to form the square out of whatever character is contained in character parameter fillCharacter. Thus, if side is 5 and fillCharacter is #, then this function should print the following:

    
    #####
    #####
    #####
    #####
    #####
    
  14. 6.24 (Separating Digits) Write program segments that accomplish each of the following:

    1. Calculate the integer part of the quotient when integer a is divided by integer b.

    2. Calculate the integer remainder when integer a is divided by integer b.

    3. Use the program pieces developed in (a) and (b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should print as follows:

      
      4  5  6  2
      
  15. 6.25 (Calculating Number of Seconds) Write a function that takes the time as three integer arguments (hours, minutes and seconds) and returns the number of seconds since the last time the clock “struck 12.” Use this function to calculate the amount of time in seconds between two times, both of which are within one 12-hour cycle of the clock.

  16. 6.26 (Celsius and Fahrenheit Temperatures) Implement the following integer functions:

    1. Function celsius returns the Celsius equivalent of a Fahrenheit temperature.

    2. Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature.

    3. Use these functions to write a program that prints charts showing the Fahrenheit equivalents of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of all Fahrenheit temperatures from 32 to 212 degrees. Print the outputs in a neat tabular format that minimizes the number of lines of output while remaining readable.

  17. 6.27 (Find the Minimum) Write a program that inputs three double-precision, floating-point numbers and passes them to a function that returns the smallest number.

  18. 6.28 (Perfect Numbers) An integer is said to be a perfect number if the sum of its divisors, including 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, because 6=1+2+3. Write a function isPerfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the divisors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.

  19. 6.29 (Prime Numbers) An integer is said to be prime if it’s divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.

    1. Write a function that determines whether a number is prime.

    2. Use this function in a program that determines and prints all the prime numbers between 2 and 10,000. How many of these numbers do you really have to test before being sure that you’ve found all the primes?

    3. Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why? Rewrite the program, and run it both ways. Estimate the performance improvement.

  20. 6.30 (Reverse Digits) Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the function should return 1367.

  21. 6.31 (Greatest Common Divisor) The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the numbers. Write a function gcd that returns the greatest common divisor of two integers.

  22. 6.32 (Quality Points for Numeric Grades) Write a function qualityPoints that inputs a student’s average and returns 4 if a student’s average is 90–100, 3 if the average is 80–89, 2 if the average is 70–79, 1 if the average is 60–69 and 0 if the average is lower than 60.

  23. 6.33 (Coin Tossing) Write a program that simulates coin tossing. For each toss of the coin, the program should print Heads or Tails. Let the program toss the coin 100 times and count the number of times each side of the coin appears. Print the results. The program should call a separate function flip that takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time.]

  24. 6.34 (Guess-the-Number Game) Write a program that plays the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays the following:

    
    I have a number between 1 and 1000.
    Can you guess my number?
    Please type your first guess.
    

    The player then types a first guess. The program responds with one of the following:

    
    1. Excellent! You guessed the number!
       Would you like to play again (y or n)?
    2. Too low. Try again.
    3. Too high. Try again.
    

    If the player’s guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player “zero in” on the correct answer.

  25. 6.35 (Guess-the-Number Game Modification) Modify the program of Exercise 6.34 to count the number of guesses the player makes. If the number is 10 or fewer, print "Either you know the secret or you got lucky!" If the player guesses the number in 10 tries, then print "Ahah! You know the secret!" If the player makes more than 10 guesses, then print "You should be able to do better!" Why should it take no more than 10 guesses? Well, with each “good guess” the player should be able to eliminate half of the numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.

  26. 6.36 (Recursive Exponentiation) Write a recursive function power(base, exponent) that, when invoked, returns

    baseexponent

    For example, power(3, 4) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. Hint: The recursion step would use the relationship

    baseexponent=basebaseexponent1

    and the terminating condition occurs when exponent is equal to 1, because

    base1=base
  27. 6.37 (Fibonacci Series: Iterative Solution) Write a nonrecursive version of the function fibonacci from Fig. 6.26.

  28. 6.38 (Towers of Hanoi) In this chapter, you studied functions that can be easily implemented both recursively and iteratively. In this exercise, we present a problem whose recursive solution demonstrates the elegance of recursion, and whose iterative solution may not be as apparent.

    The Towers of Hanoi is one of the most famous classic problems every budding computer scientist must grapple with. Legend has it that in a temple in the Far East, priests are attempting to move a stack of golden disks from one diamond peg to another (Fig. 6.31). The initial stack has 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from one peg to another under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. Three pegs are provided, one being used for temporarily holding disks. Supposedly, the world will end when the priests complete their task, so there is little incentive for us to facilitate their efforts.

    Fig. 6.31 Towers of Hanoi for the case with four disks.

    Let’s assume that the priests are attempting to move the disks from peg 1 to peg 3. We wish to develop an algorithm that prints the precise sequence of peg-to-peg disk transfers.

    If we were to approach this problem with conventional methods, we would rapidly find ourselves hopelessly knotted up in managing the disks. Instead, attacking this problem with recursion in mind allows the steps to be simple. Moving n disks can be viewed in terms of moving only n – 1 disks (hence, the recursion), as follows:

    1. Move n – 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.

    2. Move the last disk (the largest) from peg 1 to peg 3.

    3. Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area. The process ends when the last task involves moving n = 1 disk (i.e., the base case). This task is accomplished by simply moving the disk, without the need for a temporary holding area. Write a program to solve the Towers of Hanoi problem. Use a recursive function with four parameters:

      1. The number of disks to be moved

      2. The peg on which these disks are initially threaded

      3. The peg to which this stack of disks is to be moved

      4. The peg to be used as a temporary holding area

      Display the precise instructions for moving the disks from the starting peg to the destination peg. To move a stack of three disks from peg 1 to peg 3, the program displays the following moves:

      13 (This means move one disk from peg 1 to peg 3.)123213212313
  29. 6.39 (Towers of Hanoi: Iterative Version) Any program that can be implemented recursively can be implemented iteratively, although sometimes with more difficulty and less clarity. Try writing an iterative version of the Towers of Hanoi. If you succeed, compare your iterative version with the recursive version developed in Exercise 6.38. Investigate issues of performance, clarity and your ability to demonstrate the correctness of the programs.

  30. 6.40 (Visualizing Recursion) It’s interesting to watch recursion “in action.” Modify the factorial function of Fig. 6.25 to print its local variable and recursive call parameter. For each recursive call, display the outputs on a separate line and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text.

  31. 6.41 (Recursive Greatest Common Divisor) The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y, defined recursively as follows: If y is equal to 0, then gcd(x, y) is x; otherwise, gcd(x, y) is gcd(y, x % y), where % is the remainder operator. [Note: For this algorithm, x must be larger than y.]

  32. 6.42 (Distance Between Points) Write function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double.

  33. 6.43 What does the following program do?

    
     1   // Exercise 6.44: ex06_44.cpp
     2   // What does this program do?
     3   #include <iostream>
     4   using namespace std;
     5
     6   int mystery(int, int); // function prototype
     7
     8   int main() {
     9      cout << "Enter two integers: ";
    10      int x{0};
    11      int y{0};
    12      cin >> x >> y;
    13      cout << "The result is " << mystery(x, y) << endl;
    14   }
    15
    16   // Parameter b must be a positive integer to prevent infinite recursion
    17   int mystery(int a, int b) {
    18      if (1 == b) { // base case
    19         return a;
    20      }
    21      else { // recursion step
    22         return a + mystery(a, b - 1);
    23      }
    24   }
    
  34. 6.44 After you determine what the program of Exercise 6.43 does, modify the program to function properly after removing the restriction that the second argument be nonnegative.

  35. 6.45 (Math Library Functions) Write a program that tests as many of the math library functions in Fig. 6.2 as you can. Exercise each of these functions by having your program print out tables of return values for a diversity of argument values.

  36. 6.46 (Find the Error) Find the error in each of the following program segments and explain how to correct it:

    1.  

      
      float cube(float); // function prototype
      
      cube(float number) { // function definition
         return number * number * number;
      }
      
    2. int randomNumber{srand()};

    3.  

      
      float y{123.45678};
      int x;
      x = y;
      cout << static_cast<float>(x) << endl;
      
    4.  

      
      double square(double number) {
         double number{0};
         return number * number;
      }
      
    5.  

      
      int sum(int n) {
         if (0 == n) {
            return 0;
         }
         else {
            return n + sum(n);
         }
      }
      
  37. 6.47 (Craps Game Modification) Modify the craps program of Fig. 6.9 to allow wagering. Package as a function the portion of the program that runs one game of craps. Initialize variable bankBalance to 1000 dollars. Prompt the player to enter a wager. Use a while loop to check that wager is less than or equal to bankBalance and, if not, prompt the user to reenter wager until a valid wager is entered. After a correct wager is entered, run one game of craps. If the player wins, increase bankBalance by wager and print the new bankBalance. If the player loses, decrease bankBalance by wager, print the new bankBalance, check on whether bankBalance has become zero and, if so, print the message "Sorry. You busted!" As the game progresses, print various messages to create some “chatter” such as "Oh, you're going for broke, huh?", "Aw cmon, take a chance!" or "You're up big. Now's the time to cash in your chips!".

  38. 6.48 (Circle Area) Write a C++ program that prompts the user for the radius of a circle, then calls inline function circleArea to calculate the area of that circle.

  39. 6.49 (Pass-by-Value vs. Pass-by-Reference) Write a complete C++ program with the two alternate functions specified below, each of which simply triples the variable count defined in main. Then compare and contrast the two approaches. These two functions are

    1. function tripleByValue that passes a copy of count by value, triples the copy and returns the new value and

    2. function tripleByReference that passes count by reference via a reference parameter and triples the original value of count through its alias (i.e., the reference parameter).

  40. 6.50 (Unary Scope Resolution Operator) What’s the purpose of the unary scope resolution operator?

  41. 6.51 (Function Template minimum) Write a program that uses a function template called minimum to determine the smaller of two arguments. Test the program using integer, character and floating-point number arguments.

  42. 6.52 (Function Template maximum) Write a program that uses a function template called maximum to determine the larger of two arguments. Test the program using integer, character and floating-point number arguments.

  43. 6.53 (Find the Error) Determine whether the following program segments contain errors. For each error, explain how it can be corrected. [Note: For a particular program segment, it’s possible that no errors are present.]

    1.  

      
      template <typename A>
      int sum(int num1, int num2, int num3) {
         return num1 + num2 + num3;
      }
      
    2.  

      
      void printResults(int x, int y) {
         cout << "The sum is " << x + y << '
      ';
         return x + y;
      }
      
    3.  

      
      template <A>
      A product(A num1, A num2, A num3) {
         return num1 * num2 * num3;
      }
      
    4.  

      
      double cube(int);
      int cube(int);
      
  44. 6.54 (C++11 Random Numbers: Modified Craps Game) Modify the program of Fig. 6.9 to use the new C++11 random-number generation features shown in Section 6.9.

  45. 6.55 (C++11 Scoped enum) Create a scoped enum named AccountType containing constants named SAVINGS, CHECKING and INVESTMENT.

  46. 6.56 (Function Prototypes and Definitions) Explain the difference between a function prototype and a function definition.

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

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