If we need to repeat a task three times we can use sequential control:
task();
task();
task();
But if the task needs to be repeated 99 times, sequential control is a drag. Worse yet, sometimes we don't know in advance how many times we need to repeat a task. There are even tasks that must be repeated infinitely many times.
For these situations we need a control structure that allows us to repeat or iterate a task many times, an indeterminite number of times, or infinitely many times. Java provides three closely related control structures for doing this:
while, do, and for
Here's
the syntax for the while loop:
while(CONDITION) STATEMENT;
Here's
the semantics of the while loop:
do STATEMENT; while (CONDITION);
Semantically,
a do loop executes its body, then its condition. Thus, even if the condition is
initially false, the body will be executed at least once.
We
can formalize the semantics of the do loop by translating it into an equivalent
while loop:
{ STATEMENT; while(CONDITION) STATEMENT; }
Here's
the syntax:
for(EXPRESSION; EXPRESSION; EXPRESSION) STATEMENT;
The
first expression is called the initialization; it may also be a sequence of
local declarations. The second expression is called the condition; the last
expression is called the update. The command is called the body. All are
optional:
for(INITIALIZATION; CONDITION; UPDATE) BODY;
Semantically,
the initialization is executed once. This usually declares and/or initializes
loop control variables. Next, the condition is evaluated. If the value of the
condition is not 0 or false, then the body is executed, then the update is
executed. The update expression usually updates any loop control variables. The
condition is re-executed and the process repeats, ending when and only when the
condition becomes 0 or false. Of course this may never happen, which makes the
designation "determinate loop" a bit of a misnomer.
Here's
the equivalent while loop:
{
INITIALIZATION;
while (CONDITION)
{
BODY;
UPDATE;
}
}
The
most common for loop uses a loop control variable to control the number of
times the body will be executed. The following command
for(int lcv = 5; 0 <= lcv; lcv--)
System.out.println("count = " + lcv);
produces the output:
5
4
3
2
1
0
Of
course the body of a for loop may be another for loop.
The following command:
for(int row = 0; row <= height; row++)
{
for(int col = 0; col <= width; col++)
{
System.out.print("*");
}
System.out.println();
}
produces the output:
***********
***********
***********
***********
***********
***********
Notice
that the body of the inner loop is a block command containing a single command.
Technically, it's not necessary to make a single command into a block, but it
is good programming practice as it makes the program more readable.