Introduction to repetition (loops)

Loops have four sections

Three types of looping control in Java:

The while loop

The while loop is the most general kind of loop --- when in doubt, you can always use a while loop.

Form: while ( repetitionCondition )

Interpretation: If repetitionCondition is true, the loopStatement is executed and the repetitionCondition is reevaluated and tested. As soon as repetitionCondition is false, the statement after the loop is executed. Draw picture.

Example 10: Pick random numbers between 0 and 5 until you get a 3. Output the number of values you picked.

   Random r = new Random();
   int numberValues = 0;
   while (r.nextInt(6) != 3)
      numberValues ++; 
   System.out.println("We had to draw " + (numberValues+1) + " values");
Why does the last line use numberValues + 1 ?

The loopStatement for the while or other loop constructs can be a single statement, as above, or it can be a block of statements enclosed in braces.

The repetitionCondition in the while can be anything, but when the while loop is used for counting, the form will be:

                  //<== initialize counter
   while ( /* test whether the counter exceeded the limit? */ )   {
                     // <== stuff to repeat                    
                     // <== update the loop counter

Example 11: Output the numbers between 1 and 10 using a while loop.

   int num = 1;
   while (num <= 10) {
      System.out.println( num + " ");
      num ++;
The while repeats as long as the expression in the parenthesis evaluates to true .

The for loop

The for loop is naturally designed for counting out a specific number.

Form: for( initialization ; test ; update )

Interpretation: The initialization is done first. Then the test is performed. If the test is true , execute the body of the loop. Then perform the update step and do the test again. As soon as the test is false, control passes to the statement after the for loop. (Draw a flow chart.)

Example 12: Print n asterisks on a line
   for (count = 0; count < n; count++)

The do - while loop

Form: do
while ( repetition-condition )

Interpretation: The loopStatement is executed before the repetition-condition is tested. If the repetition-condition is true, repeat the loop again.

Example 13: Write code to prompt the user to enter an integer greater than 0.

   int theNumber;
   Scanner scan = new Scanner(;
   do {
      System.out.println("Please enter an integer > 0");
      theNumber = scan.nextInt();
   } while (theNumber <= 0);
   System.out.println("The number you have entered is " + theNumber);

When the loopStatement of a do - while is a block, we put the while on the same line as the closing brace to illustrate that the while is part of a previous do = while rather than the start of a new while loop.

Flow of control