Laboratory 9

Lets go looping now, everybody is learning how

 

Objective

Being able to repeatedly execute statements of interest is a powerful programming mechanism. In this laboratory you will gain practice with the Java for and do-while looping statements.

Note that not everybody has gone over the do-while statement.  Therefore, that section is optional.

 

Key Concepts

 

Getting Started

Using the procedures in the previous laboratories, copy the files Count1.java, Count2.java, ForSum.java, Fraction.java, DoSum.java, and Rectangles.java for your manipulation.  Three of these files (ForSum.java, Fraction.java, and Rectangles.java) will need to be submitted.

 

For looping

A for statement has the following form.

   for ( ForInit ; ForExpression  ; ForUpdate  ) Action

The execution of the ForInit initialization step begins the execution of a for loop. The initialization step is executed only once per execution of the for loop.

The ForExpression is the test expression for the for loop. If the test expression evaluates to true, the body of the loop (i.e., the Action) is executed. After the body of the loop is executed (iterated), the ForUpdate step is executed.

The test expression is then reevaluated. If the test expression again evaluates to true, the body of the loop (i.e., the Action) is reiterated. After the body of the loop iterates, the ForUpdate step is executed again. This process continues until the test expression evaluates to false.

public class Count1 {
   public static void main(String[] args) {
 
      int counter1 = 0;
      int counter2 = 0;
 
      for (int i = 1; i <= 10; ++i) {
         ++counter1;
      }
 
      for (int j = 1; j <= 15; ++j) {
         ++counter2;
      }
 
      System.out.println("counter1: " + counter1);
      System.out.println("counter2: " + counter2);
   }
}
public class Count2 {
   public static void main(String[] args) {
      int counter1 = 0;
      int counter2 = 0;
 
      for (int i = 1; i <= 10; ++i) {
         ++counter1;
         for (int j = 1; j <= 15; ++j) {
            ++counter2;
         }
      }
 
      System.out.println("counter1: " + counter1);
      System.out.println("counter2: " + counter2);
   }
}
public class ForSum {
   public static void main(String[] args) {
 
      // determine the minimum and maximum number in the series to sum
 
      Scanner stdin = new Scanner (System.in);
 
      System.out.print("Enter a number: ");
      int minNumber = stdin.nextInt();
 
      System.out.print("Enter a bigger number: ");
      int maxNumber = stdin.nextInt();
      System.out.println();
 
      // make sure user followed the instructions
 
      if ( maxNumber < minNumber ) {
         // the user did not follow the instructions – print message
         // and exit
 
         System.out.println("Unacceptable interval: " + minNumber
             + " ... " + maxNumber + " program exits.");
         System.exit(0);
      }
 
      // user followed instructions sum the numbers from minNumber
      // to maxNumber
      // in the series
 
     int sum = 0;    // keeps track of the running total of the
                     // terms. Nothing has been added so sum is 0
       
 
     int currentNumber = minNumber;
    
     while (currentNumber <= maxNumber ) {
        sum = sum + currentNumber;
        ++currentNumber;
     }
 
     // running total is now the actual total
 
     System.out.println("The sum from 1 to " + minNumber
             + " ... " + maxNumber + " is " + sum);
  }
}


Debugging

Improper initialization statements and termination conditions often are causes of incorrect program behavior. The following example illustrates some common mistakes.

public class Fraction {
   public static void main(String[] args) {
 
      Scanner stdin = new Scanner (System.in);
 
      System.out.print("Enter a positive integer: ");
      int n = stdin.nextInt();
 
      double fraction = ((double)1)/n;
 
      double total = 0;        // running sum of the fraction total
 
      for (int loopCounter = 0; total < 1; ++loopCounter) {
         total = total + fraction;
      }
 
      System.out.println("The total is " + total);
   }
} 

System.out.println("total: " + total + " fraction: " + fraction + " loopCounter: " + loopCounter);

stdin.nextLine();

Do-while looping

As not everybody has gone over the do-while statement, this section is optional.

A do-while statement has the following form.

do Action while ( TestExpression )

The execution of a do-while loop begins with the execution of its Action. Unlike the while and for loops, the action of a do-while loop is executed always at least once.

The test expression is then evaluated. If it evaluates to true, the action iterates again.

The test expression is then re-evaluated. If the test expression again evaluates to true, the action iterates again. This process continues until the test expression evaluates to false.


Rectangle rendering

The next exercise shows how loops can accomplish a significant amount of work using a small number of statements. You will develop a program Rectangles.java to draw a geometric picture that should resemble the following figure. The picture has five elements and each element is a series of concentric rectangles that alternate in color.
 
 
 
final int SIZE = 400;
final int CENTER_X = SIZE/2;
final int CENTER_Y = SIZE/2;
final int NUMBER_ITERATIONS = 20;
final double SCALING = 0.8;
final int OFFSET = SIZE/4;
JFrame window = new JFrame("Concentricity");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(SIZE, SIZE );
window.setVisible(true);
Graphics g = window.getGraphics();

int side = SIZE;

for (int i = 1; i <= NUMBER_ITERATIONS; i++)
      Color drawColor;
 
      if (i % 2 == 0) {
         drawColor = Color.YELLOW;
      }
      else {
         drawColor = Color.BLUE;
      }
 
      g.setColor(drawColor);
int half = side / 2;
g.fillRect(CENTER_X - OFFSET - half, CENTER_Y - OFFSET - half, side, side);

g.fillRect(CENTER_X + OFFSET - half, CENTER_Y + OFFSET - half, side, side);

g.fillRect(CENTER_X - half, CENTER_Y - half, side, side);

side = (int)(side * SCALING);


Finishing up