Kinds of Loops

 

To Loop or Not To Loop: it's a Question for Many Students

The purpose of loop statements is to repeat something many times. There are three kinds of loop statements in Java: while, for, and do..while

 

Pseudocode:
Mom says you have to eat all your peas before you get dessert.
//while loop
                               while (peas are still on the plate)
	 eat peas;

//do..while loop
do
	  eat peas;
                                 while (peas are still on the plate);
//for loop, 3 more big bites!
          for(3 bites)
	      eat peas;
//////////////////////////////////

 

do

{

loop body

}while (loop condition);

for (initialization block; loop condition; update block)

{

     loop body

}

while (loop condition)

{

loop body

}

DoLoop.gif (2274 bytes) ForLoop.gif (2930 bytes) WhileLoop.gif (2271 bytes)
 
int x=0;//counter variable
while (x!=10)//conditional expression
{
      x=x+2;  //increment x
      System.out.println(x); 
        
}//compound statement
 
//counter is the "for loop control variable" 
//and starts at 1
//counter<=3 is the condition under which the 
//loop continues
//counter++ is done at the end of each iteration
for (int counter=1;counter<=3;counter++)
     System.out.println("JAVA totally rules!");
        
int x=0; //counter variable

do

{

x=x+2; //increment x

System.out.println(x);

} while (x<10);

The "while" loop, used when you want to check a condition before the commands are executed.
 
The "for" loop, used when you know how many
 times you need to repeat commands. 
The "do..while" loop, used when you want to repeat commands until a condition is met.
The while loop is a pre-test loop. This loop will execute as long as the express being tested evaluates to true. A while loop might not execute if the controlling expression was false the first time.

The variable(s) controlling the condition must be initialized before the while statement. . Be sure to include a statement within the body of the while that will make the condition become false. If you fail to do this you will have an infinite loop.

 

 

COUNTING LOOP

A counting loop repeats instructions a certain number of times.

 

Requirements for a Counting Loop

1. Must contain the name of a control variable; any legal variable name.

2. Must contain the initial value of the control variable.

3. The control variable must be incremented or decremented through each iteration of the loop. This eliminates infinite loops.

4. The control variable must test for the final value in order to terminate the control structure

The do while loop is a post-test loop used by Java. The biggest difference between the do while loop and the while loop is that the do while loop always executes at least once because the controlling condition is not tested until the end of the loop, after the action statements execute. The do while structure may be a single or compound statement structure.

If the condition evaluates to be true, the statements will be executed again. If the condition evaluates to be false, the do/while structure will be exited.

 

  1. As we learned in class, 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 t he loop, it knows how many times to repeat.
  2. Here's a quick example of a counting loop.
  3. class Lab10p1
    {
      public static void main(String[] args) 
      {
        for (int count = 1; count <= 5; count++)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
  1. Compile and run the program. what happens here?.
  2. It's obvious that the for statement in Lab10p1 is a counting loop, because it counts from 1 to 5. However, a loop can be a counting loop when you don't know (as the programmer) how many times the loop will repeat. The only stipulation is that the comp uter must know, when the loop starts, how many times it will repeat.
  3. 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.
    
    
    class Lab10p2
    {
      public static void main(String[] args) 
      {
        int repeatTimes =0;
        TextIO.put(" how many times   ");
        repeatTimes= TextIO.getlnInt();
        
        for (int count = 1; count <= repeatTimes; count++)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
  4. Compile and run the program.
  5. When you write program Lab10p2, 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. After the user enters that number, the computer knows how many times to repeat the loop. ( The computer knows this before it starts executing the loop.)
  6. Here's an example of 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.
    import Keyboard;
    
    class Lab10p3
    {
      public static void main(String[] args)
      {
        int count = 0;
        char countAgain = Keyboard.readChar("Start counting? (y/n): ", "yn");
        while (countAgain == 'y' || countAgain == 'Y')
        {
          count++;
          System.out.println("Counting ... " + count);
          countAgain = Keyboard.readChar("Count again? (y/n): ", "yn");
        }
        System.out.println("Done");
      }
    }
  7. Compile and run the program.
  8. Lab10p3 is not a counting loop because the computer doesn't know when to stop the loop until the user tells it to stop.

The for Statement

  1. We use the for statement to make the computer execute a group of statements a specific number of times. As we've seen in the example Lab10p1, we can use the for state ment when we know (when writing the program) how many times we want the loop to repeat.
  2. Lab10p2 shows that we can use a variable for the end value of the loop. This allows the user of the program to decide the number of times the loop should repeat, rather than the programmer. We can also use a variable for the beginning value of the loop. We can use this technique to give the user of the program more control over how it executes. Here's an example.
    import Keyboard;
    
    class Lab10p4
    {
      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.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
  3. Compile and run the program. .
  4. When you run Lab10p4, you can enter a starting value greater than 5.
  5. 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. Here's an (incomplete) example.
    class Lab10p5
    {
      public static void main(String[] args)
      {
        for (int count = 5; count >= 1; ???)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
  6. Click on the file Lab10p5, and save the file as Lab10p5.java. Modify the program so it counts backward, from 5 down to 1. Compile and run the program. Write down how you modified the program to make it count backward.
  7. 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.
    class Lab10p6
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        for (int count = 0; count <= 12; count = count + 3)
        {
          System.out.println("Counting ... " + count);
        }
        System.out.println("Done");
      }
    }
  8. Click on the file Lab10p6, and save it as Lab10p6.java. Compile and run the program. what happens here?.
  9. 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 inte ger (as in all the examples so far). Here's an example of the latter possibility.
    class Lab10p7
    {
      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");
      }
    }
  10. Click on this file: Lab10p7, and save it as Lab10p7.java. Load the file into the editor and modify it so that it counts from 1.0 to 2.0 by 0.1. Write down how you changed the program. The output of the program should look something like this.
    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
  11. (Your output may look something like 1.2000000001 -- that's ok. Hint: You'll probably have to make the ending value a little over 2.0. Later in Chapter 5, we'll see why this is necessary, and why the display of floating point numbers is sometim es inexact.)

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:

    - The user may enter a specific value from the keyboard.

    - The user may click a mouse button.

    - The computer's internal clock may reach a specific time.

    - The computer is microphone may detect a sound.

    - The user may insert (or remove) a CD-ROM in the CD-ROM tray.

    - The user may insert (or remove) a diskette or tape into the computer.

    - The computer may detect a network transmission.

    - A sensor connected to the computer may send a signal to the computer. (For example, the computer may be connected to a scale in a factory. When a hopper pours enough material onto the scale, the computer may sense this and turn off the hopper.)

    -... and many other possibilities.

  3. The while statement is designed for these kinds of loops.
  4. The structure of the while statement is simple:
    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.
    class Lab10p8
    {
      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");
        }
        System.out.println("Bye!");
      }
    }
  7. Click on this file: Lab10p8, and save it as Lab10p8.java. Compile and run the program. Write down what happens when you respond 'n' to the first question. Write down what happens when you respond 'y' to the first question and 'n' to the second one.
  8. Here's another example of a program that uses a while statement for an event-controlled loop. This example shows how to use a sentinel value to mark the end of the input data. The program 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. (We saw a similar example in class that adds instead of multiplies.)
    class Lab10p9
    {
      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);
      }
    }
  9. Click on this file: Lab10p9, and save it as Lab10p9.java. Compile and run the program. Write down what the program displays when you multiply the numbers 10, 20, and 30.
  10. As we discussed in class, the while statement in Lab10p9.java looks wrong at first glance. Intuitively, the statements inside the while statements 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. Here's a version of Lab10p9 that seems more correct intuitively, but is actually wrong.
    class Lab10p10  // WRONG!!
    {
      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);
      }
    }
  11. Click on this file: Lab10p10, and save the program as Lab10p10.java. Compile the program and write down the error message the compiler generates.
  12. You can easily fix Lab10p10 so it compiles by a the initializing the variable number. Modify Lab10p10 by initializing the variable number with the value 0 (int product = 1, number = 0;). Compile the program and run it. Write down what happens when you try to multiply the numbers 10, 20, and 30.
  13. Again, this error is easy to fix. Change the initialization value of number to something other than zero. Modify Lab10p10 this way, compile the program and run it. Write down what happens when you try to multiply the numbers 10, 20, and 30. Write down why the program gives the result it does.
  14. 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.
  15. Let's take stock of what we've done to make Lab10p10 work correctly:

    - We had to give the variable number an initial value, even though the program never uses that value. This is certainly not intuitive.

    - We had to make sure that the initial value of the variable number was not the same as the sentinel value.

    - We had to add an if statement inside the while loop.

  16. With all these changes, Lab10p10 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: Lab10p9 (the one with the "upside down looking" while statement). Therefore, it's better to use the correct version (Lab10p9) than to try to patch up a version that doesn't work (Lab10p10).
  17. 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
}

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.
    class Lab10p11
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int x = 0;
        while (x < 10)
        {
          System.out.print(x);
        }
        System.out.println("Done!");
      }
    }
  3. Click on this file: Lab10p11, and save it as Lab10p11.java. Compile and run the program. Write down what happens.
  4. To stop a program with an infinite loop, press Control-C.
  5. 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" -- you won't be able to type anythin g that the computer response to (except Control-C).
  6. Try modifying Lab10p11 so it does not display the value of x inside the while statement. Compile and run the program. Write down what happens.
  7. As we discussed in class, there are many ways to accidentally write an infinite loop in Java. You need to be careful to avoid writing infinite loops. The best way to do this is to think about each loop as you write it. Make sure that there is some sta tement (or statements) in the loop body that will eventually make the condition false.

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 c hecks 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.
    class Lab10p12
    {
      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!");
      }
    }
  3. Click on the file: Lab10p12, and save it as Lab10p12.java. Compile and run the program. Write down what the program displays when you enter an invalid response, and when you enter the correct response. Why is this program probably not very useful to a young child (especially one who doesn't know the correct response)? Write down your answer.
  4. 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 conditio n is not true to begin with. Here's an example that shows the difference. This program has two loops: a while loop and an 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 o ther words, there's nothing for the loops to do.)
    class Lab10p13
    {
      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");
      }
    }
  5. Click on this file: Lab10p13, and save it as Lab10p13.java. Compile and run the program.

 

TRY THESE FOR FUN

 

TRY SELF QUIZ