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
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! ;-(
loop is an entry-condition loop. If the test
condition is FALSE to begin
with, the program never executes the body of the loop.
following program fragment prints and counts the characters of a string array:
= 0; //begin
with the first cell of array
while (i< name.length( )) // loop test condition
cout<< name[ i ] << endl; //print each character
//increment counter by 1
cout << "There are " << i << "
\*This last cout prints when the test condition is false and the loop