Exercises

  1. 5.10 Compare and contrast the if single-selection statement and the while iteration statement. How are these two statements similar? How are they different?

  2. 5.11 (Integer Division) Explain what happens when a C# app attempts to divide one integer by another. What happens to the fractional part of the calculation? How can you avoid that outcome?

  3. 5.12 (Combining Control Statements) Describe the two ways in which control statements can be combined.

  4. 5.13 (Choosing Iteration Statements) What type of iteration would be appropriate for calculating the sum of the first 100 positive integers? What type of iteration would be appropriate for calculating the sum of an arbitrary number of positive integers? Briefly describe how each of these tasks could be performed.

  5. 5.14 (Prefix vs. Postfix Increment Operators) What is the difference between the prefix increment operator and the postfix increment operator?

  6. 5.15 (Find the Error) Identify and correct the errors in each of the following pieces of code. [Note: There may be more than one error in each piece of code.]

    1. 
      if (age >= 65);
      {
         Console.WriteLine("Age greater than or equal to 65");
      }
      else
      {
         Console.WriteLine("Age is less than 65)";
      }
      
    2. 
      int x = 1, total;
      while (x <= 10)
      {
         total += x;
         ++x;
      }
      
    3. 
      while (x <= 100)
         total += x;
         ++x;
      
    4. 
      while (y > 0)
      {
         Console.WriteLine(y);
         ++y;
      
  7. 5.16 (What Does This Program Do?) What does the following app display?

    
      1   // Ex. 5.16: Mystery.cs
      2   using System;
      3
      4   class Mystery
      5   {
      6      static void Main()
      7      {
      8         int x = 1;
      9         int total = 0;
     10
     11         while (x <= 10)
     12         {
     13            int y = x * x;
     14            Console.WriteLine(y);
     15            total += y;
     16            ++x;
     17         }
     18
     19         Console.WriteLine($"Total is {total}");
     20      }
     21   }
    

For Exercises 5.175.20, perform each of the following steps:

  1. Read the problem statement.

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

  3. Write a C# app.

  4. Test, debug and execute the C# app.

  5. Process three complete sets of data.

  1. 5.17 (Gas Mileage) Drivers are concerned with the mileage their automobiles get. One driver has kept track of several tankfuls of gasoline by recording the miles driven and gallons used for each tankful. Develop a C# app that will input the miles driven and gallons used (both as integers) for each tankful. The app should calculate and display the miles per gallon obtained for each tankful and display the combined miles per gallon obtained for all tankfuls up to this point. All averaging calculations should produce floating-point results. Display the results rounded to the nearest hundredth. Use the Console class’s ReadLine method and sentinel-controlled iteration to obtain the data from the user.

  2. 5.18 (Credit-Limit Calculator) Develop a C# app that will determine whether any of several department-store customers has exceeded the credit limit on a charge account. For each customer, the following facts are available:

    1. account number,

    2. balance at the beginning of the month,

    3. total of all items charged by the customer this month,

    4. total of all credits applied to the customer’s account this month and

    5. allowed credit limit.

    The app should input all these facts as integers, calculate the new balance (= beginning balance + charges – credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit. For those whose credit limit is exceeded, the app should display the message "Credit limit exceeded". Use sentinel-controlled iteration to obtain the data for each account.

  3. 5.19 (Sales-Commission Calculator) A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5,000 worth of merchandise in a week receives $200 plus 9% of $5,000, or a total of $650. You’ve been supplied with a list of the items sold by each salesperson. The values of these items are as follows:

    
    Item        Value
    1           239.99
    2           129.75
    3            99.95
    4           350.89
    

    Develop a C# app that inputs one salesperson’s items sold for the last week, then calculates and displays that salesperson's earnings. There’s no limit to the number of items that can be sold by a salesperson.

  4. 5.20 (Salary Calculator) Develop a C# app that will determine the gross pay for each of three employees. The company pays straight time for the first 40 hours worked by each employee and time-and-a-half for all hours worked in excess of 40 hours. You’re given a list of the three employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your app should input this information for each employee, then should determine and display the employee’s gross pay. Use the Console class’s ReadLine method to input the data.

  5. 5.21 (Find the Largest Number) The process of finding the maximum value (i.e., the largest of a group of values) is used frequently in computer applications. For example, an app that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write pseudocode, then a C# app that inputs a series of 10 integers, then determines and displays the largest integer. Your app should use at least the following three variables:

    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 integer most recently input by the user.

    3. largest: The largest number found so far.

  6. 5.22 (Tabular Output) Write a C# app that uses looping to display 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
    
  7. 5.23 (Find the Two Largest Numbers) Using an approach similar to that for Exercise 5.21, find the two largest values of the 10 values entered. [Note: You may input each number only once.]

  8. 5.24 (Validating User Input) Modify the app in Fig. 5.13 to validate its inputs. For any input, if the value entered is other than 1 or 2, display the message “Invalid input,” then keep looping until the user enters a correct value.

  9. 5.25 (What Does This Program Do?) What does the following app display?

    
      1   // Ex. 5.25: Mystery2.cs
      2   using System;
      3
      4   class Mystery2
      5   {
      6      static void Main()
      7      {
      8         int count = 1;
      9
     10         while (count <= 10)
     11         {
     12            Console.WriteLine(count % 2 == 1 ? "****" : "++++++++");
     13            ++count;
     14         }
     15      }
     16   }
    
  10. 5.26 (What Does This Program Do?) What does the following app display?

    
      1   // Ex. 5.26: Mystery3.cs
      2   using System;
      3
      4   class Mystery3
      5   {
      6      static void Main()
      7      {
      8         int row = 10;
      9         int column;
     10
     11         while (row >= 1)
     12         {
     13            column = 1;
     14
     15            while (column <= 10)
     16            {
     17               Console.Write(row % 2 == 1 ? "<" : ">");
     18               ++column;
     19            }
     20
     21            --row;
     22            Console.WriteLine();
     23         }
     24      }
     25   }
    
  11. 5.27 (Dangling-else Problem) The C# compiler always associates 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)
          Console.WriteLine("x and y are > 5");
    else
       Console.WriteLine("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)
          Console.WriteLine("x and y are > 5");
       else
          Console.WriteLine("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.

  12. 5.28 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 5.27, 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)
      Console.WriteLine("*****");
      else
      Console.WriteLine("#####");
      Console.WriteLine("$$$$$");
      
    2. 
      if (x < 10)
      {
      if (y > 10)
      Console.WriteLine("*****");
      }
      else
      {
      Console.WriteLine("#####");
      Console.WriteLine("$$$$$");
      }
      
  13. 5.29 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 5.27, modify the given code to produce the output shown in each part of the problem. 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)
    Console.WriteLine("@@@@@");
    else
    Console.WriteLine("#####");
    Console.WriteLine("$$$$$");
    Console.WriteLine("&&&&&");
    
    1. Assuming that x = 5 and y = 8, the following output is produced:

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

      @@@@@

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

      
      @@@@@
      &&&&&
      
    4. Assuming that x = 5 and y = 7, the following output is produced.

      
      #####
      $$$$$
      &&&&&
      
  14. 5.30 (Square of Asterisks) Write an app that prompts the user to enter the size of the side of a square, then displays a hollow square of that size made of asterisks. Your app should work for squares of all side lengths between 1 and 20. If the user enters a number less than 1 or greater than 20, your app should display a square of size 1 or 20, respectively.

  15. 5.31 (Palindromes) A palindrome is a sequence of characters 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 an app that reads in a five-digit integer and determines whether it’s a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value. [Hint: Use the remainder and division operators to pick off the number’s digits one at a time, from right to left.]

  16. 5.32 (Displaying the Decimal Equivalent of a Binary Number) Write an app that inputs an integer containing only 0s and 1s (i.e., a binary integer) and displays its decimal equivalent. [Hint: Picking the digits off a binary number is similar to picking the digits off a decimal number, which you did in Exercise 5.31. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left has a positional value of 10, then 100, then 1000 and so on. The decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left has a positional value of 2, then 4, then 8 and so on. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8, or 13.]

  17. 5.33 (Checkerboard Pattern of Asterisks) Write an app that uses only the output statements

    
    Console.Write("* ");
    Console.Write(" ");
    Console.WriteLine();
    

    to display the checkerboard pattern that follows. A Console.WriteLine method call with no arguments outputs a single newline character. [Hint: Iteration statements are required.]

    
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    * * * * * * * *
     * * * * * * * *
    
  18. 5.34 (Multiples of 2) Write an app that keeps displaying in the console window the powers of the integer 2—namely, 2, 4, 8, 16, 32, 64 and so on. Loop 40 times. What happens when you run this app?

  19. 5.35 (What’s Wrong with This Code?) What is wrong with the following statement? Provide the correct statement to add 1 to the sum of x and y.

    
    Console.WriteLine(++(x + y));
    
  20. 5.36 (Sides of a Triangle) Write an app that reads three nonzero values entered by the user, then determines and displays whether they could represent the sides of a triangle.

  21. 5.37 (Sides of a Right Triangle) Write an app that reads three nonzero integers, then determines and displays whether they could represent the sides of a right triangle.

  22. 5.38 (Factorials) The factorial of a nonnegative integer n is written as n! (pronounced “n factorial”) and is defined as follows:

    n!=n·(n1)·(n2)··1(for values of n greater than or equal to 1)

    and

    n!=1(for n=0)

    For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. Write an app that reads a nonnegative integer and computes and displays its factorial.

  23. 5.39 (Infinite Series: Mathematical Constant e) Write an app that estimates the value of the mathematical constant e by using the formula

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

    The predefined constant Math.E (class Math is in the System namespace) provides a good approximation of e. Use the WriteLine method to output both your estimated value of e and Math.E for comparison.

  24. 5.40 (Infinite Series: ex) Write an app that computes the value of ex by using the formula

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

    Compare the result of your calculation to the return value of the method call

    
    Math.Pow(Math.E, x)
    

    [Note: The predefined method Math.Pow takes two arguments and raises the first argument to the power of the second. We discuss Math.Pow in Section 6.6.]

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

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