Lab 7: Iteration

Instructions: Follow the steps given in each section below. For each question, click the radio button next to the most correct answer. When you are finished, type your name and your partner at the end of the document, write down your answers for your records, then press the Submit button. You may submit just one lab response. If you submit more than one, only the first one counts for a grade.

Contents

A. Purpose

This lab is designed to review loop control structures in Java. By the end of this lab, you should have a good grasp of the difference between counting loops and event-controlled loops. You should also be able to tell when to use each of the loop control structures in Java: the for statement, the while statement, and the do-while statement. You should also know how to avoid writing an infinite loop in a program, and how to stop an infinite loop from the keyboard.

This lab also covers material on numerical accuracy and introduces you to representation of integers and floating-point numbers in Java. By the end of this lab, you should be able to explain how to avoid round-off errors in programming, and how to avoid overflow conditions when using integers.

B. Kinds of Loops

  1. There are two kinds of loops: counting loops and event-controlled loops. We've been writing counting loops when using the for statement and turtle graphics. Remember that a loop is a counting loop if, when the computer starts the loop, it "knows" how many times to repeat.
  2. Program DemonstrateCountingLoop.java below shows an example of a counting loop.
  3. SimpleCountingLoop.javaDownload (Help)
    // Demonstrates a counting loop
    
    public class SimpleCountingLoop
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        for (int count = 1; count <= 5; count++)
        {
          System.out.print(count);
        }
        System.out.println("!!");
      }
    }
    SimpleCountingLoop.javaDownload (Help)

  4. Download SimpleCountingLoop.java, then compile and run it.
  5. Question
    1
    What does SimpleCountingLoop.java display when it runs?

    1. 1!!
    2. 1234!!
    3. 5!!
    4. 12345!!
    5. 15!!

  6. It's obvious that the for statement in SimpleCountingLoop.java is a counting loop, because it counts -- it even uses the variable count. However, a loop can be a counting loop when you (the programmer) don't know how many times the loop will repeat. The only stipulation is that the computer must know, when the loop starts, how many times it will repeat.
  7. Here's an example of a loop that the computer knows, when the loop starts, how many times to repeat the loop -- even though you don't know when you are writing the program.
  8. UserControlledCountingLoop.javaDownload (Help)
    // Demonstrates a counting loop in which the user controls
    // the number of iterations
    
    import Keyboard;
    
    public class UserControlledCountingLoop
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int repeatTimes = Keyboard.readInt("Count to: ");
        
        for (int count = 1; count <= repeatTimes; count++)
        {
          System.out.print(count);
        }
        System.out.println("!!");
      }
    }
    UserControlledCountingLoop.javaDownload (Help)

  9. Download UserControlledCountingLoop.java, then compile and run it.
  10. Question
    2
    When you run UserControlledCountingLoop.java and answer 7 to the prompt, the program displays

    1. !!
    2. 17!!
    3. 1234567!!
    4. 123456!!
    5. 234567!!

  11. When you write program UserControlledCountingLoop.java, you don't know what the user will enter in response to the prompt. However, when the program runs, the user must enter a number before the loop starts. After the user enters that number, the computer knows how many times to repeat the loop.
  12. Program NotCountingLoop.java contains a loop that's not a counting loop -- it's event-controlled. Notice that the program doesn't use a for statement; it uses a while statement to control the loop.
  13. NotCountingLoop.javaDownload (Help)
    // Demonstrates a loop that's not a counting loop
    
    import Keyboard;
    
    public class NotCountingLoop
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        char countAgain = Keyboard.readChar("Start? (y/n): ", "yn");
        while (countAgain == 'y' || countAgain == 'Y')
        {
          System.out.println("Looping ... ");
          countAgain = Keyboard.readChar("Again? (y/n): ", "yn");
        }
        System.out.println("Done");
      }
    }
    NotCountingLoop.javaDownload (Help)

  14. Download NotCountingLoop.java, then compile and run the program.
  15. Question
    3
    What happens when you run NotCountingLoop.java?

    1. It keeps displaying Start? (y/n) over and over without stopping -- there's no user control.
    2. It counts up to 10, then stops.
    3. It displays nothing.
    4. It keeps displaying Again? (y/n) over and over without stopping -- there's no user control.
    5. It keeps asking whether to loop again; when you type n, the program stops.

  16. The loop statement in NotCountingLoop.java is not a counting loop because the computer doesn't know when to stop the loop until the user tells it to stop.

C. The for Statement

  1. We've used the for statement to make the computer execute a group of statements a specific number of times. As we've seen in previous examples in this lab, we can use the for statement when we know (when writing the program) how many times we want the loop to repeat.
  2. We've seen that we can use a variable for the end value of the loop. This allows the user of the program, rather than the programmer, to decide the number of times the loop should repeat. We can also use a variable for the beginning value of the loop. We can use this technique to give the user more control over how the program executes. The program CountFromValue.java shows an example.
  3. CountFromValue.javaDownload (Help)
    // Shows that the starting value of a for statement can
    // be a variable.
    
    import Keyboard;
    
    public class CountFromValue
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int startAt = Keyboard.readInt("Start counting at: ");
    
        for (int count = startAt; count <= 5; count++)
        {
          System.out.print(count);
        }
        System.out.println("!!");
      }
    }
    CountFromValue.javaDownload (Help)

  4. Download CountFromValue.java, then compile and run the program.
  5. Question
    4
    What does CountFromValue.java display when you enter a starting value greater than 5, such as 8?

    1. 76!!
    2. 876!!
    3. !!
    4. 8765!!
    5. 765!!

  6. Sometimes, you'll want a loop to count backward rather than forward. This is easy to do with the for statement -- simply make the increment part count down instead of up. Program CountDown.java below shows an (incomplete) example.
  7. CountDown.javaDownload (Help)
    // Shows how to count down rather than up.
    // Replace ??? with the correct expression.
    
    public class CountDown
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        for (int count = 5; count >= 1; ???)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
    CountDown.javaDownload (Help)

  8. Download program CountDown.java, then modify it so it counts backward, from 5 down to 1. Compile and run the program.
  9. Question
    5
    What did you replace ??? with in CountDown.java?

    1. 1 - count
    2. count - 1
    3. -1
    4. count--
    5. count++

  10. Sometimes, you'll want a loop to count by something other than one (either forward or backward). Here's an example. Notice the increment part of the for statement -- it counts by three rather than 1.
  11. CountByThree.javaDownload (Help)
    // Shows how to make a counting loop count by a value
    // besides 1 (or -1)
    
    public class CountByThree
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        for (int count = 0; count <= 12; count = count + 3)
        {
          System.out.print(count);
        }
        System.out.println("!!");
      }
    }
    CountByThree.javaDownload (Help)

  12. Download CountByThree.java, then compile it and run it.
  13. Question
    6
    What does CountByThree.java display when it runs?

    1. 036912!!
    2. 012!!
    3. 0369!!
    4. 369!!
    5. 36912!!

  14. There are many other ways to use the for statement to count. For example, you could "count" by multiplication or division instead of addition or subtraction. You can also use a floating-point variable as the counting variable, instead of using an integer (as in all the examples so far). Here's an example of the latter possibility.
  15. FloatingPointCount.javaDownload (Help)
    // Demonstrates use of a for statement that uses floating-point
    // values.
    // Replace each occurrence of ??? with a floating-point value, so
    // the program counts from 1.0 to 2.0 by 0.1
    
    public class FloatingPointCount
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        for (double count = ???; count < ???; count = count + ???)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
    FloatingPointCount.javaDownload (Help)

  16. Download program FloatingPointCount.java, and modify it so that it counts from 1.0 to 2.0 by 0.1. The output of the program should look something like this. (The computer may display numbers that are very close to these, such as 1.2000000000000002 -- that's ok.)
  17. Counting ... 1.0
    Counting ... 1.1
    Counting ... 1.2
    Counting ... 1.3
    Counting ... 1.4
    Counting ... 1.5
    Counting ... 1.6
    Counting ... 1.7
    Counting ... 1.8
    Counting ... 1.9
    Counting ... 2.0
    Done

    Question
    7
    How did you modify FloatingPointCount.java so it produces the output shown above?

    1. The first ??? is 1.1; the second ??? is 2.0; the third ??? is 0.1
    2. The first ??? is 1.0; the second ??? is 2.1; the third ??? is 0.1
    3. The first ??? is 1.0; the second ??? is 2.0; the third ??? is 1.0
    4. The first ??? is 1.1; the second ??? is 2.1; the third ??? is 0.1
    5. The first ??? is 1.0; the second ??? is 2.0; the third ??? is 0.1

  18. You may think that it would make more sense if the for statement in FloatingPointCount.java were written this way:
  19. for (double count = ???; count <= ???; count = count + ???)

    That is, with <= instead of <. This may look more correct, but it doesn't work very well.

    Question
    8
    What does FloatingPointCount.java display if you change the for statement to use count <= 2.0?

    1. It keeps going after 2.0 (2.1, 2.2, ...).
    2. It doesn't compile.
    3. It stops with an error message.
    4. It counts up to 1.9, then stops.
    5. It displays nothing.

  20. (Later on in this lab we'll see why the first approach with < is necessary, and why the display of floating point numbers is sometimes inexact.)

D. The while Statement

  1. The for statement is designed for counting loops. Many loops in programs, however, are not counting loops, but event-controlled. That is, the computer may not know, when it begins executing the loop, how many times the loop will repeat.
  2. As the name suggests, an event-controlled loop is controlled by an event. That is, there must be some condition that tells the computer whether to stop the loop or execute it again. There are many possibilities for such conditions:
  3. The while statement is designed for these kinds of loops. The structure of the while statement is simple:
  4. while (condition)
    {
      statements;
    }

  5. The action of the while statement is intuitive: as long as the condition is true, the computer executes the statements in the body of the while statement.
  6. Here's an example. Notice that this program has no counting variable whatsoever. Also, the computer has no way of knowing how many times the user will answer 'y' to the question. Therefore, this is a an event-controlled loop -- not a counting loop.
  7. DemonstrateWhile.javaDownload (Help)
    // Demonstrates use of the while statement
    
    public class DemonstrateWhile
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        char sayAgain = Keyboard.readChar("Say hello? (y/n): ", "yn");
        while (sayAgain == 'y' || sayAgain == 'Y')
        {
          System.out.println("H E L L O !!");
          sayAgain = Keyboard.readChar("Say hello again? (y/n): ", "yn");
        }
      }
    }
    DemonstrateWhile.javaDownload (Help)

  8. Download DemonstrateWhile.java, then compile and run the program.
  9. Question
    9
    What does DemonstrateWhile.java display when you run it and respond 'n' to the first question?

    1. It displays displays H E L L O !!, then displays Say hello? (y/n):, then stops.
    2. It displays Say hello again? (y/n): again, then stops.
    3. It displays nothing after the first question.
    4. It displays Say hello? (y/n): again, then stops.
    5. It displays displays H E L L O !!, then stops.

    Question
    10
    How many times does DemonstrateWhile.java display H E L L O !! when you run it and respond 'y' to the first question and 'n' to the second question?

    1. three times
    2. none
    3. one time
    4. two times
    5. four times

  10. Program DemonstrateSentinel.java below uses a while statement for an event-controlled loop. This program shows how to use a sentinel value to mark the end of the input data. It reads integers from the user and multiplies them. When the user enters 0, that tells the program to stop reading input data. The number 0 is the sentinel -- it marks the end of the data but is not part of the data.
  11. DemonstrateSentinel.javaDownload (Help)
    // Shows how to use a sentinel value to mark the end of data
    
    public class DemonstrateSentinel
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int product = 1, number;
    
        number = Keyboard.readInt("Enter first number (0 to stop): ");
        while (number != 0)
        {
          product = product * number;
          number = Keyboard.readInt("Enter next number (0 to stop): ");
        }
        System.out.println("The product is " + product);
      }
    }
    DemonstrateSentinel.javaDownload (Help)

  12. Download DemonstrateSentinel.java, then compile it and run it.
  13. Question
    11
    What does program DemonstrateSentinel.java display as the product of 10, 20, and 30?

    1. 0
    2. 6000
    3. 600
    4. 60
    5. 60000

    Question
    12
    What values did you enter into program DemonstrateSentinel.java to find the product of 10, 20, and 30?

    1. 10, 20, 30, ::
    2. 10, 20, 30, end
    3. 10, 20, 30, STOP
    4. 10, 20, 30
    5. 10, 20, 30, 0

  14. The while statement in DemonstrateSentinel.java looks wrong at first glance. Intuitively, the statements inside the while statement seem backward -- it seems as though the input statement should come before the multiplication. Also, it seems strange to have two input statements: one before the loop and one at the end of the loop. Program DemonstrateSentinel2.java below is a modification of DemonstrateSentinel.java that seems more correct intuitively, but is actually wrong.
  15. DemonstrateSentinel2.javaDownload (Help)
    // Shows how to use a sentinel value to mark the end of data
    // WRONG!!
    
    public class DemonstrateSentinel2
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int product = 1, number;
    
        while (number != 0)
        {
          number = Keyboard.readInt("Enter next number (0 to stop): ");
          product = product * number;
        }
        System.out.println("The product is " + product);
      }
    }
    DemonstrateSentinel2.javaDownload (Help)

  16. Download DemonstrateSentinel2.java and compile it. (It won't compile.) You can easily fix DemonstrateSentinel2.java so it compiles by initializing the variable number. (Modify DemonstrateSentinel2.java by initializing the variable number with the value 0 like this:
    int product = 1, number = 0;
    (Note that we didn't need to initialize this variable in DemonstrateSentinel.java.) Compile the program and run it.
  17. Question
    13
    After fixing DemonstrateSentinel2.java as described above (initializing number to 0), what does the program display as the product of 10, 20, and 30?

    1. 1
    2. 600
    3. 60
    4. 0
    5. 6000

  18. Again, this error is easy to fix. Change the initialization value of number to something other than zero. Modify DemonstrateSentinel2.java this way, compile the program and run it.
  19. Question
    14
    After fixing DemonstrateSentinel2.java as described above (initializing number to something besides 0), what does the program display as the product of 10, 20, and 30?

    1. 0
    2. 60
    3. 600
    4. 1
    5. 6000

  20. This error is also easy to fix -- you simply need to add an if statement inside the body of the loop, so the multiplication doesn't happen when the user enters the sentinel value.
  21. Question
    15
    After fixing DemonstrateSentinel2.java as described above (add an if statement inside the body of the loop), what does the program display as the product of 10, 20, and 30?

    1. 6000
    2. 60
    3. 1
    4. 0
    5. 600

  22. Let's take stock of what we've done to make DemonstrateSentinel2.java work correctly:
  23. With all these changes, DemonstrateSentinel2.java doesn't look as "natural" as it did when we started. It works, but it's actually less intuitive and more tricky than the correct version of the program: DemonstrateSentinel.java (the one with the "upside down looking" while statement). Therefore, it's better to use the correct version (DemonstrateSentinel.java) than to try to patch up a version that doesn't work (DemonstrateSentinel2.java).
  24. The structure of a typical event-controlled loop with the while statement looks like this.

initialize the variable used in the condition
while (the variable is not equal to sentinel value)
{
  do whatever needs to be done inside the loop
  get the next value of the variable used in the condition
}

E. Infinite Loops

  1. Any infinite loop is one that doesn't end. The computer gets "stuck" in the loop and can't escape, because the condition never becomes false.
  2. Here's a simple example of an infinite loop that uses the while statement.
  3. InfiniteLoop.javaDownload (Help)
    // Demonstration of an infinite loop
    
    public class InfiniteLoop
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int x = 0;
        while (x < 10)
        {
          System.out.print(x);
        }
        System.out.println("Done!");
      }
    }
    InfiniteLoop.javaDownload (Help)

  4. Download program InfiniteLoop.java, then compile and run the program. (To stop a program with an infinite loop, press Control-C.)
  5. Question
    16
    What does InfiniteLoop.java display when it runs?

    1. 0123456789101112...
    2. 123456789101112...
    3. Zeros
    4. 0 1 2 3 4 5 6 7 8 9 10 11 12 ...
    5. 1 2 3 4 5 6 7 8 9 10 11 12 ...

  6. Usually, an infinite loop is not so obvious when you run the program. There may not be an output statement in the loop body that shows you the loop is infinite. In those cases, the computer will appear to "lock up" -- the computer won't respond to anything you type (except Control-C).
  7. Try modifying InfiniteLoop.java so it does not display the value of x inside the while statement. Compile and run the program, so you know how this kind of infinite loop works.
  8. There are many ways to accidentally write an infinite loop in Java, so you need to be careful whenever you write a loop. The best way to avoid writing an infinite loop is to think about each loop as you write it. Make sure that there is some statement (or statements) in the loop body that will eventually make the condition false.

F. The do-while Statement

  1. We've explored the main event-controlled loop structure in Java: the while statement. The other event-controlled loop in Java is the do-while statement. The only difference (other than syntax) between these two statements is that the while statement checks the condition before each iteration of the loop. The do-while statement checks the condition after each iteration of the loop.
  2. Here's an example of a do-while statement in a program. The program is supposed to help young children with addition.
  3. DemonstrateDoWhile.javaDownload (Help)
    // Demonstration of a do-while loop
    
    public class DemonstrateDoWhile
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int response;
        
        do
        {
          response = Keyboard.readInt("What's the sum of 3 and 4? ");
        } while (response != 7);
        
        System.out.println("That's right!");
      }
    }
    DemonstrateDoWhile.javaDownload (Help)

  4. Download DemonstrateDoWhile.java, then compile and run the program.
  5. Question
    17
    Why is this program probably not very useful to a young child (especially one who doesn't know the correct response)?

    1. The program displays the question after asking for the response.
    2. The program should ask for a floating-point number response.
    3. It doesn't display a help message if the child types the wrong answer.
    4. The program doesn't compute the sum correctly.
    5. The program displays the question before asking for the response.

  6. Because the do-while statement condition is at the bottom of the loop, the computer will always execute the body of a do-while statement at least once. In contrast, the computer may not execute the body of a while statement that all -- if the condition is not true to begin with. Here's an example that shows the difference. This program has two loops: a while loop and a do-while loop. Each loop starts with the variable number at 100, and keeps adding 1 as long as that variable is less than 10. (In other words, there's nothing for the loops to do.)
  7. CompareWhileAndDoWhile.javaDownload (Help)
    // This program compares a while statement with a do-while
    // statement
    
    public class CompareWhileAndDoWhile
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int number;
    
        System.out.println("Begin while statement ---");
        number = 100;
        while (number < 10)
        {
          System.out.println(number);
          number++;
        }
        System.out.println("--- End while statement");
        
        System.out.println("Begin do-while statement ---");
        number = 100;
        do
        {
          System.out.println(number);
          number++;
        } while (number < 10);
        System.out.println("--- End do-while statement");
      }
    }
    CompareWhileAndDoWhile.javaDownload (Help)

  8. Download CompareWhileAndDoWhile.java, then compile and run the program.
  9. Question
    18
    The output of CompareWhileAndDoWhile.java looks something like this:
     Begin while statement ---
    ??????
    --- End while statement
    Begin do-while statement ---
    ??????
    --- End do-while statement
    What does the program display in place of the ?????? symbols?

    1. 100 for the first part, nothing for the second part.
    2. Nothing for the first part, 100 for the second part.
    3. The numbers 100 down to 10 for the first part, nothing for the second part.
    4. Nothing for the first part, the numbers 100 down to 10 for the second part.
    5. The numbers 100 down to 10 for the first part, the numbers 100 down to 11 for the first part.

    Question
    19
    Why does CompareWhileAndDoWhile.java display different values in the while loop than it does in the do-while loop?

    1. The computer can't execute a while loop that has no body.
    2. The computer executes the body of a while loop at least once.
    3. A do-while loop has a negative condition.
    4. The computer executes the body of a do-while loop at least once.
    5. The computer can't execute a do-while loop that has no body.

  10. Whenever you think you might need at do-while statement in a program, you should think twice about it. In the 1970s, studies done with the programming language Pascal showed that test-at-the-bottom loops (like do-while) only account for about five per cent of all loops. Therefore, when you write a loop, the odds are pretty good that you should use a while statement (for an event-controlled loop), or for statement (for a counting loop). Very seldom do you need to use a do-while statement. You should use a do-while statement if you want the loop body to execute at least once, though.

G. Numerical Accuracy

  1. Download the following program, AddTo1.java, then compile the program and run it.
  2. AddTo1.java Download (Help)
    // Add up 0.10 until the sum is 1.0
    
    public class AddTo1
    {
      public static void main(String[] args)
      {
    
        double total = 0.0;
    
        while (total != 1.0)
        {
          total = total + 0.10;
          System.out.println("Total so far: " + total);
        }
        System.out.println("Done");
      }
    }
    AddTo1.java Download (Help)

    Question
    20
    What happens when you run AddTo1.java?

    1. The program displays nothing.
    2. The program displays numbers from 0.0 to 1.0, then stops.
    3. The program keeps displaying numbers after it reaches 1.0.
    4. The program displays numbers from 0.1 to 1.0, then stops.
    5. The program displays numbers from 0.0 to 1.1, then stops.

  3. The program AddTo1.java shows that floating-point numbers are often approximations. Therefore, we must be careful when using floating-point arithmetic in a program, because we might not get the result we expect.
  4. There are three ways to fix AddTo1.java:
  5. Question
    21
    Which of the following while statements correctly uses integers instead of floating-point numbers in AddTo1.java?

    1. double total = 0;
      

      while (total != 1) { total = total + 1/10; System.out.println("Total so far: " + total); } System.out.println("Done");


    2. double total = 0.0;
      

      while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    3. int total = 0;
      

      while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    4. int total = 0.0;
      

      while (total != 10) { total = total + 1; System.out.println("Total so far: " + total); } System.out.println("Done");


    5. int total = 0;
      

      while (total != 10) { total = total + 1; System.out.println("Total so far: " + total / 10.0); } System.out.println("Done");

    Question
    22
    Which of the following while statements correctly uses <= instead of == in AddTo1.java?

    1. double total = 0.0;
      

      while (total != 1.1) { while (total <= 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } } System.out.println("Done");


    2. double total = 0.0;
      

      while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    3. double total = 0.0;
      

      while (total != 1.1) { total <= total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    4. double total = 0.0;
      

      while (total != 0.9) { if (total <= 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } } System.out.println("Done");


    5. double total = 0.0;
      

      while (total <= 0.9) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");

    Question
    23
    Which of the following while statements correctly uses tests for a small difference instead of checking for inequality in AddTo1.java?

    1. double total = 0.0;
      

      while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    2. double total = 0.0;
      

      while (total - 1.0 > 0.001) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    3. double total = 0.0;
      

      while (1.0 - total > 0.001) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    4. double total = 0.0;
      

      while (Math.abs(total - 1.0) < 0.001) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");


    5. double total = 0.0;
      

      while (Math.abs(total - 1.0) > 0.001) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done");

  6. Not every floating-point number is an approximation -- the computer can store some floating-point numbers exactly. For example, the computer can store whole numbers (such as 10.0 or -3.0) exactly. It can also store many fractional numbers, such as 0.25, exactly. Program Squares.java below that illustrates this fact. This program asks you to enter a number. It then finds the square root of that number, and squares the square root. The result (the square of the square root of a number) should give you what you started with.
  7. Squares.java Download (Help)
    // This program takes the square root of a number, squares that
    // number, and compares the result squared with the original
    
    import Keyboard;
    
    public class Squares
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        System.out.println("This program takes the square root of a ");
        System.out.println("number, squares that number, and compares");
        System.out.println("the result squared with the original.");
        // Get the number
        double value = Keyboard.readDouble("Enter a number: ");
    
        // Take the square root
        double squareRootOfValue = Math.sqrt(value);
        System.out.println("The square root of " + value + " is "
                           + squareRootOfValue);
    
        // Find the square of the square root
        double squareOfSquareRootOfValue
            = squareRootOfValue * squareRootOfValue;
        System.out.println("The square of the square root of "
                           + value + " is " + squareOfSquareRootOfValue);
                           
        // Compare the square of the square root with the original
        if (squareOfSquareRootOfValue == value)
        {
          System.out.println("The square of the square root of " + value
                             + " is equal to " + value);
        }
        else
        {
          System.out.println("The square of the square root of " + value
                             + " is NOT equal to " + value);
          System.out.println("The difference is "
                             + (value - squareOfSquareRootOfValue));
        }
      }
    }
    Squares.java Download (Help)

  8. Download program Squares.java, then compile and run the program.
  9. Question
    24
    Which of the following numbers is not equal to the square of its square root, as computed in a Java program?

    1. 3969
    2. 8281
    3. 5487
    4. 15129
    5. 55225

    Question
    25
    Which of the following numbers is equal to the square of its square root, as computed in a Java program?

    1. 9834
    2. 2330
    3. 84785
    4. 45984
    5. 3249

  10. The computer sometimes gives inaccurate results when it does arithmetic on numbers that are very different in size. The book shows this problem with a a simulation of a space probe on its way to Proxima Centauri, the nearest star to earth. The program goes into an infinite loop, because it subtracts 1 from a very large number.
  11. The program InaccurateArithmetic.java shows this same problem.
  12. InaccurateArithmetic.java Download (Help)
    // Subtracts one from 4.067815793829482158E18 and shows the result
    
    import Keyboard;
    
    public class InaccurateArithmetic
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        double centimetersToProximaCentauri = 4.067815793829482158E18;
        double centimetersToProximaCentauriMinus1
               = centimetersToProximaCentauri - 1;
    
        System.out.println("centimetersToProximaCentauri is supposed to be --> "
                           + "4.067815793829482158E18");
        System.out.println("centimetersToProximaCentauri is stored as -------> "
                           + centimetersToProximaCentauri);
        System.out.println("centimetersToProximaCentauri - 1 is stored as ---> "
                           + centimetersToProximaCentauriMinus1);
                           
        if (centimetersToProximaCentauri == centimetersToProximaCentauriMinus1)
        {
          System.out.println("The last two numbers are the same");
        }
        else
        {
          System.out.println("The last two numbers are different");
        }
      }
    }
    InaccurateArithmetic.java Download (Help)

  13. Download program InaccurateArithmetic.java, then compile and run it.
  14. Question
    26
    How does program InaccurateArithmetic.java store the number 4.067815793829482158E18?

    1. As 4.0678E18
    2. As 4.067815793829482E18
    3. As 4.0678157938294822E18
    4. As 4.06781579382948216E18
    5. As 4.06781579382948215E18

    Question
    27
    What does InaccurateArithmetic.java say the difference is between 4.067815793829482158E18 and 4.067815793829482158E18 - 1?

    1. 12
    2. 1
    3. 0
    4. 518
    5. 1E10

  15. InaccurateArithmetic.java shows that subtracting 1 from a very large number (4.067815793829482158E18) may not give the correct result, because the computer does not store all the significant digits of this very large number.
  16. Although not as common, it is also possible to get incorrect results when using integer arithmetic. Usually, the problem will be because of overflow -- this is when the number is too large for the computer to store. Most of the time, overflow conditions result from an incorrect ordering of arithmetic operations. For example, the program Overflow.java below should display the result of 2000 times 1000 times 1000 times 4 divided by 4, because the result is within the range of the type int. However, it doesn't work because of overflow.
  17. Overflow.java Download (Help)
    // Illustrates integer overflow
    
    import Keyboard;
    
    public class Overflow
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        System.out.println(2000 * 1000 * 1000 * 4 / 4);
      }
    }
    Overflow.java Download (Help)

  18. Download Overflow.java, then compile and run it.
  19. Question
    28
    What should Overflow.java display if it evaluates the expression correctly?

    1. 200000000000
    2. 400000000
    3. 0
    4. 2000000000
    5. 40000000000

    Question
    29
    What does Overflow.java actually display?

    1. 90834980
    2. -147483648
    3. 12394E15
    4. -290394
    5. 32987590

  20. The problem with Overflow.java is that the order of the operations gives a temporary result that is outside the bounds of the type int. (Remember that the range of the type int is roughly -2 billion to +2 billion.) The first operator in Overflow.java is 2000 * 1000: this results in 2,000,000. The next operator multiplies this result by 1000, giving 2,000,000,000. The next operator multiplies us this result by 4, giving 8,000,000,000 -- which is out of bounds. The computer can't store this number, so it stores "junk" in its place. Therefore, when the program divides this "junk" by 4, it gets more junk for an answer.
  21. Overflow.java is easy to fix -- simply rearrange the order of the operators so intermediate results don't go outside the range of int. Load Overflow.java into your editor and rearrange the operations so that the program displays the correct result. (Don't remove any operations.)

    Question
    30
    Which of the following expressions will result in an overflow condition?

    1. 4000/2000 * 100000
    2. 5000 * 5000 * 1000 / 100
    3. 20000 / 10 + 50000 * 600
    4. 800 + 500000 / 1000 * 40000
    5. 10000 * 5000 / 100 * 3000

  22. Program Overflow.java was easy to fix, but many real-life programs are not so straightforward. It's often difficult to figure out how to rearrange operators to avoid overflow. However it's essential to avoid overflow (especially in intermediate results!) if you want correct output.


Turn in this Assignment

First name:
Last name:
Partner's last name:

Write down your answers for your records, then press the Submit button below to turn in the lab assignment.