Howdy. 

Loops. 

C211: Accumulators. 

Loops allow us to write code in accumulator passing style. 

while (...) { // condition 
  ... // body 


Execute the body as long as the condition remains true. 

Problem: print the first 20 even integers. 

         number   number % 2 == 0  counter 
            0         true           1
            1         false          1 
            2         true           2
            3         false          2
            4         true           3
           ...                 
                                    20   end 

public class LabFour {
  public static void main(String[] args) {
    int 
      number = 0, // number to investigate 
      counter = 0;  // how many numbers I have printed already 
    while (counter < 20) {
      if (number % 2 == 0) {
        System.out.println( counter + ". " + number ); 
        counter++; // counter = counter + 1; 
        // System.out.println(counter); 
      }
      number++; 
    }
  }
}

Be careful and accept the program is yours. 

The for loop. 

for ( INIT ; COND ; STEP ) {
  BODY


This is equivalent to: 

  INIT

  while (COND) {
    BODY

    STEP
  }

public class LabFour {
  public static void main(String[] args) {
    Scanner speckles = new Scanner(System.in); 
    int counter = 0;
    double sum = 0; 
    while ( true ) {
      System.out.print("Enter number: "); 
      String line = speckles.nextLine(); 
      if (line.equals("bye")) {
        break;  
      }
      double number = Double.parseDouble( line ); 
      counter = counter + 1; 
      sum = sum + number; 
      System.out.println("Current average: " + (sum / counter)); 
    } // end of while 
    System.out.println("Thanks for using this program."); 
  }
}

This runs like this:

Welcome to DrJava.  Working directory is C:\Users\dgerman\Desktop
> run LabFour
Enter number:  [DrJava Input Box]
Current average: 3.0
Enter number:  [DrJava Input Box]
Current average: 2.0
Enter number:  [DrJava Input Box]
Current average: 3.0
Enter number:  [DrJava Input Box]
Thanks for using this program.
>

--








Mark Logan Daniel Jared Nathan Austin Trevor
Qin Walter Aleksa Judy Hallie Adam James Brennan Jacquelyn 
Nick Yiming Jingzhe Zac Paul Morgan Alex Ong William 
Jon Grant MAR Mohan Jack Lauren 

Here's an example of how we solved this problem in C211:

; example:
;       number       divisor       factors
; --------------------------------------------------
;        150           2            empty
;         75           2            (cons 2 empty)
;         75           3            (cons 2 empty)
;         25           3            (cons 3 (cons 2 empty))
;         25           4            (cons 3 (cons 2 empty))
;         25           5            (cons 3 (cons 2 empty))
;          5           5            (cons 5 (cons 3 (cons 2 empty)))
;          1           5            (cons 5 (cons 5 (cons 2 (cons 2 empty))))