Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use                                                                                      

The while loop

The while loop allows programs to repeat a statement or series of statements, over and over, as long as a certain test condition is true.  The format is shown in the box to the right.

The test condition must be enclosed in parentheses.  The block of code is known as the body of the loop and is enclosed in braces and indented for readability.  (The braces are not required if the body is composed of only ONE statement.)  Semi-colons follow the statements within the block only.

When a program encounters a while loop, the test condition is evaluated first.  If it is TRUE, the program executes the body of the loop.  The program then returns to the test condition and reevaluates.  If still TRUE, the body executes again.  This cycle of testing and execution continues until the test condition evaluates to FALSE.  If you want the loop to eventually terminate, something within the body of the loop must affect the test condition.  Otherwise, a disastrous INFINITE LOOP is the result!  ;{

The while loop is an entry-condition loop.  If the test condition is FALSE to begin with, the program never executes the body of the loop.

The following program fragment prints and counts the characters of a string variable:

String name="Corky";
int i = 0; //begin with the first cell of string
while (i < name.length( )) // loop test condition
     //print each cell on a new line
     i++;             //increment counter by 1
System.out.println("There are "+ i + " characters.");
/*This last statement prints when the test condition is false and the loop terminates*/



while(test condition)
     block of code;



iteration - doing the same thing again and again.


Check out the Demo "while" loop fragments.

Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use