Iteration
Home Up Boolean Operators Classes Conditionals Iteration Methods

 

The iterative constructs in Java are very similar to the ones that are found in C.   For each Java looping construct, a general template is given, followed by a specific example.  To learn more about the Java looping constructs, consult a language reference manual.

For Loops

General Template:

for (initialization; entry condition; increment stuff)
{
    body of loop
}

The initialization is performed at the very beginning of the loop.  The entry condition is tested each time before the body of the loop is executed.  If the entry condition is true, the body of the loop is executed.  The increment stuff is performed following the body of the loop.

Specific Example (sums the integers from 1 through 10):

sum = 0;
for (int i = 1; i <= 10; i++)
{
   sum = sum + i;
}

While Loops

General Template:

while (entry condition)
{
   loop body
}

The entry condition is tested each time before the body of the loop is executed.  If the entry condition is true, the body of the loop is executed.

Specific Example (sums the integers from 1 through 10):

sum = 0;
i = 1;
while (i <= 10)
{
   sum = sum + i;
   i = i + 1;
}

Do Loops

General Template:

do
{
   loop body
} while (entry condition);

The entry condition is tested each time after the body of the loop is executed.  Thus, the loop body is guaranteed to execute once.  If the entry condition is true, the body of the loop is executed again.

Specific Example (sums the integers from 1 through 10):

sum = 0;
i = 1;
do
{
   sum = sum + i;
   i = i + 1;
}   while (i <= 10);