Loops

Home Up Search Java 2 API C++ Resources

Loops are used to repeatedly perform a task.    That task may or may not depend on how many times the loop has been iterated.

There are two main types of loops:  "for" and "while".

"For" and "while" loops are both optimized tail-recursions.

While loops:

"While" loops repeat a process while some condition is true.

Syntax:

while( conditional_expression)
{
      [body of loop]
}

The conditional _expression is an expression that evaluates to a boolean value (true/false).   Examples of valid expresssions:

  •  true
  •  false
  •  x < maxX
  • jCheckbox.isSelected()

The conditional expression is evaluated first and if it evaluates to true, then the body of the loop is executed.    The conditional is then evaluated again and the body is executed again if it is true.   However, if the conditional evaluates to false, then then the body is not executed and the program continues at the line immediately after the while block.

Do-While Loops:

Do-while loops are a special variant of a normal while loop.   While a regular while loop always evaluates the conditional before attempting to execute the body of the loop, a do-while loop evaluates the conditional after executing the body.    This insures that the body of the loop always gets executed at least once.

Syntax:

do
{
       [body of loop]
}
while( conditional_expression);

For Loops:

For-loops are a specialized syntax for a while-loop which iterates in specific manner.    For loops are most commonly used when the loop body needs to execute a specific number of times, for instance, when processing the elements of an array.

Syntax:

for( [initialization expression]; [conditional expression]; [incremental expression])
{
            [body of loop]
}       

This is equivalent to a while loop as such:

[initialization statement];

while([conditional expression])
{
            [body of loop]
            [incremental statement]
}       


The initialization statement is a statement that is used to initialize anything the loop may need before the start of the loop.   There can be multiple statements here separated by commas.   Most commonly, the initialization statement declares and initializes some sort of counter or index value.

The conditional expression is the same as in a while loop--it determines whether or not the body will be executed.  Like a while loop, for loops always check the conditional before attempting to execute the body.   Most commonly, the conditional statement checks to see if the counter or index value has reached its maximum (extrema) value.    If the conditional evaluates to false, the loop terminates.

The incremental statement is a statement that is executed after the body loop body.  It is executed only if the body is executed.     It is used to adjust anything necessary before retesting the conditional.   There can be multiple incremental statements separated by commas.   Most commonly, the incremental statement increments (decrements) the counter or index value.

Loop Control Commands

There are two commands that are useful for controlling a loops behavior dynamically:  break and continue

break:  This statement causes the nearest enclosing loop to immediately terminate.   This is used to force the termination of the loop.  It is usually used in conjunction with an if statement to terminate the loop if some condition is met.  Note that if there are nested loops, the outer loop does not terminate, only the loop directly enclosing the break statement.

continue:  This statement causes the loop to immediately jump to the end of the loop body and continue executing there.   In the case of a while and do-while loops, this means the conditional is evaluated.   In the case of a for loop, the incremental statement is executed and then the conditional.   This is very useful for terminating just that iteration of the loop body, but to continue the loop itself.

Examples

While-loop that has a 50% chance of executing the loop body:

while(Math.random() < 0.5)
{
     System.out.println("Still in the loop!");
}

Squaring every element in an array:

for(int index=0;index<myArray.length;index++)
{
    myArray[index] *= myArray[index];
}

Checking for an input:

do
{
    s = jTextfield.getText();
}
while(s.equals("done"));

Find the first occurance of something in an array:

for(int i=0; i< array.length;i++)
{
     if(array[i] == specialNumber)
     {
            break;
     }
}

Append text to a text area, putting a new line if the word "stop" is entered and quitting if "done" is entered:

while(true)
{
     String s = jTextfield.getText();
     if(s.equals("stop")
     {
          jTextArea.append("\n");
         continue;
     }
    
    if(s.equals("done")
    {
          break;
    }
    jTextArea.append(s);
}