Which LOOP should I use????

  • while:  the loop must repeat until a certain "condition" is met.  If the "condition" is FALSE at the beginning of the loop, the loop is never executed.  The "condition" may be determined by the user at the keyboard.  The "condition" may be a numeric or an alphanumeric entry.  This is a good, solid looping process with applications to numerous situations.

 

  • do-while:  operates under the same concept as the while loop except that the do-while will always execute the body of the loop at least one time.  (Do-while is an exit-condition loop -- the condition is checked at the end of the loop.)  This looping process is a good choice when you are asking a question, whose answer will determine if the loop is repeated.

 

  • for:  the loop is repeated a "specific" number of times, determined by the program or the user.  The loop "counts" the number of times the body will be executed.  This loop is a good choice when the number of repetitions is known, or can be supplied by the user.

The following program fragments print the numbers 1 - 20.  Compare the different looping procedures.  Remember, there are always MANY possible ways to prepare code!

do-while:

int ctr = 1;
do
{
    cout<< ctr++ <<"\n"; 
}
while (ctr <= 20);


for:

int ctr;
for(ctr=1;ctr<=20; ctr++)
{
     cout<< ctr <<"\n";

 

while:

int ctr = 1;
while (ctr < = 20)
{
     cout<< ctr++ <<"\n";
}

 

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