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 called 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 the condition is TRUE, the program executes the body of the loop.  The program then returns to the test condition and reevaluates.  If the condition is still TRUE, the body executes again.  This cycle of testing and execution continues until the test condition evaluates to 0 or 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 array:

apstring name="Corky";
i = 0;            //begin with the first cell of array
while (i< name.length( ))    // loop test condition
      cout<< name[ i ] << endl;  //print each character
      i++;                            //increment counter by 1
cout << "There are " << i << " characters.\n";
\*This last cout 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.




  Return to Topic Menu | Computer Science Main Page | | Terms of Use