Exercises

  1. 6.5 Describe the four basic elements of counter-controlled iteration.

  2. 6.6 Compare and contrast the while and for iteration statements.

  3. 6.7 Discuss a situation in which it would be more appropriate to use a dowhile statement than a while statement. Explain why.

  4. 6.8 Compare and contrast the break and continue statements.

  5. 6.9 Find and correct the error(s) in each of the following segments of code:

    1. 
      For (i = 100, i >= 1, ++i)
      {
         Console.WriteLine(i);
      }
      
    2. The following code should display whether integer value is odd or even:

      
      switch (value % 2)
      {
         case 0:
            Console.WriteLine("Even integer");
         case 1:
            Console.WriteLine("Odd integer");
      }
      
    3. The following code should output the odd integers from 19 to 1:

      
      for (int i = 19; i >= 1; i += 2)
      {
         Console.WriteLine(i);
      }
      
    4. The following code should output the even integers from 2 to 100:

      
      counter = 2;
      
      do
      {
         Console.WriteLine(counter);
         counter += 2;
      } While (counter < 100);
      
  6. 6.10 (What Does This Code Do?) What does the following app do?

    
      1    // Exercise 6.10 Solution: Printing.cs
      2    using System;
      3
      4    class Printing
      5    {
      6       static void Main()
      7       {
      8          for (int i = 1; i <= 10; ++i)
      9          {
     10             for (int j = 1; j <= 5; ++j)
     11             {
     12                Console.Write('@');
     13             }
     14
     15             Console.WriteLine();
     16          }
     17       }
     18    }
    
  7. 6.11 (Find the Smallest Value) Write an app that finds the smallest of several integers. Assume that the first value read specifies the number of values to input from the user.

  8. 6.12 (Product of Odd Integers) Write an app that calculates the product of the odd integers from 1 to 7.

  9. 6.13 (Factorials) Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. Write an app that evaluates the factorials of the integers from 1 to 5. Display the results in tabular format. What difficulty might prevent you from calculating the factorial of 20?

  10. 6.14 (Modified Compound-Interest Program) Modify the compound-interest app (Fig. 6.6) to repeat its steps for interest rates of 5, 6, 7, 8, 9 and 10%. Use a for loop to vary the rate.

  11. 6.15 (Displaying Triangles) Write an app that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be displayed by a single statement of the form Console.Write('*'); which causes the asterisks to display side by side. A statement of the form Console.WriteLine(); can be used to move to the next line. A statement of the form Console.Write(' '); can be used to display a space for the last two patterns. There should be no other output statements in the app. [Hint: The last two patterns require that each line begin with an appropriate number of blank spaces.]

    
    (a)                 (b)                  (c)                (d)
    *                   **********           **********                  *
    **                  *********             *********                 **
    ***                 ********               ********                ***
    ****                *******                 *******               ****
    *****               ******                   ******              *****
    ******              *****                     *****             ******
    *******             ****                       ****            *******
    ********            ***                         ***           ********
    *********           **                           **          *********
    **********          *                             *         **********
    
  12. 6.16 (Displaying a Bar Chart) One interesting application of computers is to display graphs and bar charts. Write an app that reads three numbers between 1 and 30. For each number that’s read, your app should display the same number of adjacent asterisks. For example, if your app reads the number 7, it should display *******.

  13. 6.17 (Calculating Sales) A website sells three products whose retail prices are as follows: product 1, $2.98; product 2, $4.50; and product 3, $9.98. Write an app that reads a series of pairs of numbers as follows:

    1. product number

    2. quantity sold

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

  14. 6.18 (Modified Compound-Interest Program) In the future, you may work with other programming languages that do not have a type like decimal which supports precise monetary calculations. In those languages, you should perform such calculations using integers. Modify the app in Fig. 6.6 to use only integers to calculate the compound interest. Treat all monetary amounts as integral numbers of pennies. Then break the result into its dollars and cents portions by using the division and remainder operations, respectively. Insert a period between the dollars and the cents portions when you display the results.

  15. 6.19 Assume that i = 1, j = 2, k = 3 and m = 2. What does each of the following statements display?

    1. Console.WriteLine(i == 1);

    2. Console.WriteLine(j == 3);

    3. Console.WriteLine((i >= 1) && (j < 4));

    4. Console.WriteLine((m <= 99) & (k < m));

    5. Console.WriteLine((j >= i) || (k == m));

    6. Console.WriteLine((k + m < j) | (3 - j >= k));

    7. Console.WriteLine(!(k > m));

  16. 6.20 (Calculating the Value of π) Calculate the value of π from the infinite series

    π=443+4547+49411+...

    Display a table that shows the value of π approximated by computing one term of this series, by two terms, by three terms, and so on. How many terms of this series do you have to use before you first get 3.14? 3.141? 3.1415? 3.14159?

  17. 6.21 (Pythagorean Triples) A right triangle can have sides whose lengths are all integers. The set of three integer values for the side lengths of a right triangle is called a Pythagorean triple (http://en.wikipedia.org/wiki/Pythagorean_triple). The side lengths must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an app to find all Pythagorean triples for side1, side2 and the hypotenuse, all no larger than 500. Use a triple-nested for loop that tries all possibilities. This method is an example of “brute-force” computing. You’ll learn in more advanced computer science courses that there are many interesting problems for which there’s no known algorithmic approach other than using sheer brute force.

  18. 6.22 (Modified Triangle Program) Modify Exercise 6.15 to combine your code from the four separate triangles of asterisks such that all four patterns display side by side. Make clever use of nested for loops.

  19. 6.23 (Displaying a Diamond) Write an app that displays the following diamond shape. You may use output statements that display a single asterisk (*), a single space or a single newline character. Maximize your use of iteration (with nested for statements) and minimize the number of output statements.

    
        *
       ***
      *****
     *******
    *********
     *******
      *****
       ***
        *
    
  20. 6.24 (Modified Diamond Program) Modify the app you wrote in Exercise 6.23 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond. Your app should then display a diamond of the appropriate size.

  21. 6.25 (Structured Equivalent of break Statement) A criticism of the break statement and the continue statement (in a loop) is that each is unstructured. Actually, break and continue 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 an app and replace it with a structured equivalent. [Hint: The break statement exits a loop from the body of the loop. The other way to exit 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 develop here to remove the break statement from the app in Fig. 6.13.

  22. 6.26 (What Does This Code Do?) What does the following code segment do?

    
    for (int i = 1; i <= 5; ++i)
    {
       for (int j = 1; j <= 3; ++j)
       {
          for (int k = 1; k <= 4; ++k)
          {
             Console.Write('*');
          }
    
          Console.WriteLine();
       }
    
       Console.WriteLine();
    }
    
  23. 6.27 (Structured Equivalent of continue Statement) Describe in general how you would remove any continue statement from a loop in an app and replace it with some structured equivalent. Use the technique you develop here to remove the continue statement from the app in Fig. 6.14.

  24. 6.28 (Modified AutoPolicy Class) Modify class AutoPolicy in Fig. 6.11 to validate the two-letter state codes for the northeast states. The codes are: CT for Connecticut, MA for Massachusetts, ME for Maine, NH for New Hampshire, NJ for New Jersey, NY for New York, PA for Pennsylvania and VT for Vermont. In the State property’s set accessor, use the logical OR (||) operator (Section 6.11.2) to create a compound condition in an ifelse statement that compares the method’s argument with each two-letter code. If the code is incorrect, the else part of the ifelse statement should display an error message. In later chapters, you’ll learn how to use exception handling to indicate that a method received an invalid value.

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

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