Which LOOP should I use????
  • while:  the loop must repeat until a certain "condition" is metIf 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
{
  System.out.println(ctr);
  ctr++; 
}
while (ctr <= 20);

for:
int ctr;
for(ctr=1;ctr<=20; ctr++)
{
   System.out.println(ctr); 

while:
int ctr = 1;
while (ctr < = 20)
{
  System.out.println(ctr); 
  ctr++;
}

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com