Week 4 lecture topics

Iteration (repetition) in Java

There are three forms of iteration as follows :-

  1. The counted, or for loop.
  2. The while loop, and
  3. The do loop.

Of these, the only one actually needed to write programs is the while loop. The others are there for programmer convenience in certain situations.

We will consider the for loop in the next lecture. Here we will concentrate on the other two.

The while loop

This is used when some boolean condition determines when the loop is to finish and the number of iterations is not known in advance. Its form is simply :-

        while ( <boolean condition> ) {
           //statements in loop
        } //end while
Here the boolean condition is evaluated before each attempt to execute the statements. If it evaluates to true the statements are executed, if false the loop terminates.

It is possible for the condition to evaluate to false immediately, in which case the loop never executes.

Example code :-

    int count = 0;                    //declare and initialise a count variable
    while ( count < 100 ) {           //loop until count >= 100
       System.out.println("I must write a hundred lines");
       count++;                       //increment variable count
    } //end while

Note :-

The do loop

This is confusingly similar to the while loop so great care is needed. The form of this is :-

        do {
           //statements in loop
        } while ( <boolean condition> ) ;
Notice the position of the while condition after the closing brace. This loop will always execute at least once as the test is not performed until the statements have been executed.

The previous example could be coded with a do loop as follows :-

    int count = 0;                //declare and initialise a count variable
    do {                          //start of loop
       System.out.println("I must write a hundred lines");
       count++;                   //increment variable count
    } while (count < 100 );

Finally, remember that loops and if statements can be nested inside each other to any depth.

There is also a switch statement which we shall meet in the next lecture.

Prematurely terminating a loop

Sometimes you wish to break out of a loop when a condition arises without actually completing the statements.

This can be achieved with the break statement. For instance, the loop :-

        while ( true ) {
           System.out.println("Another line of text");
           System.out.println("Still looping");
        } //end while

will execute for ever as the conditional expression is the boolean value true.

Another way of making this loop terminate and not print the second line on the last iteration is :-

        int count = 0; 
        while ( true ) {
           count++; 
           System.out.println("Another line of text");
           if ( count == 100 ) break;
           System.out.println("Still looping");
        } //end while

Notice the if statement above. When a control structure - if, while, for, do - only has a single statement within it, (and only then), the braces can be omitted.

Frequently, in such cases, the statement can be placed on the same line as here. Hence :-

     if ( count == 100 ) {
        break;
     } //end if

     if ( count == 100 )
        break;

and  if ( count == 100 ) break;
are all valid.

Nested loops and the break statement

It is possible to nest control structures within each other and this applies to while and do loops as much as any other.

Consider the following nested loop :-

    int count1 = 0, count2 = 0;
    while (count1 < 2 ) {
       count2 = 0;
       while (count2 < 3 ) {
          System.out.println("Count 1 = " + count1 + " Count 2 = " + count2);
          count2++;
       } //end while
       count1++;
    } //end while
this results in the output :-

Count 1 = 0 Count 2 = 0
Count 1 = 0 Count 2 = 1
Count 1 = 0 Count 2 = 2
Count 1 = 1 Count 2 = 0
Count 1 = 1 Count 2 = 1
Count 1 = 1 Count 2 = 2

If we place a break in the inner loop :-

    int count1 = 0, count2 = 0;
    while (count1 < 2 ) {
       count2 = 0;
       while (count2 < 3 ) {
          System.out.println("Count 1 = " + count1 + " Count 2 = " + count2);
          count2++;
          if ( count2 == 2 ) break;
       } //end while
       count1++;
    } //end while
the effect is to break out of the inner loop but stay in the outer loop and the output would be :-

Count 1 = 0 Count 2 = 0
Count 1 = 0 Count 2 = 1
Count 1 = 1 Count 2 = 0
Count 1 = 1 Count 2 = 1

If we wanted to break out of all looping, we have to give the loops labels and then refer to them in the break statement as follows :-

    int count1 = 0, count2 = 0;
    outer:while (count1 < 2 ) {
       count2 = 0;
       inner:while (count2 < 3 ) {
          System.out.println("Count 1 = " + count1 + " Count 2 = " + count2);
          count2++;
          if ( count2 == 2 ) break outer;
       } //end inner:while
       count1++;
    } //end outer:while
The resulting output is now :-

Count 1 = 0 Count 2 = 0
Count 1 = 0 Count 2 = 1

Loops only need a label if we wish to refer to them in a break statement as here. (so the inner label is not needed).

Example use of while and do loops


/* Application class to print multiplication tables
   Written by P. Martin
   Date 9/9/00
*/
public class Example {

   public static void main(String[] args) {
      int value = 1, count = 1;

      //print the table heading

      System.out.println("Multiplication tables");
      System.out.println();
      System.out.print("Value ");
      while (count <= 10 ) {
         System.out.print(" x " + count);
         count++;
      } //end while
      System.out.println(); 

      while ( value <= 10 ) {

         //print the table line

         System.out.print(value);
         count = 1;
         while (count <= 10) {                 
            System.out.print(" " + value * count);
            count++;
         } //end while

         value++;   //next value
      } //end while
 
   } //end main

} //end class Example

Common errors made by students

The following errors are commonly made :-


Ten Key Points
  1. Always indent after an opening brace until the corresponding close brace.
  2. Comment the end of a while loop to show what the brace refers to.
  3. Ensure that the loop will terminate - condition becomes false.
  4. Use a do loop if statements must be executed at least once.
  5. Use a break statement if the loop may need to be exited in the middle.
  6. Do not make excessive use of break statements if there is another way.
  7. Loop labels are simple identifiers - normal rules.
  8. Use labels if need to break out several levels.
  9. Dispense with braces if loop contains only one statement, but
  10. Still indent unless statement is put on same line.