(^446) | Exceptions and Additional Control Structures
The syntax template for a forstatement follows:
Expression is the condition that continues the loop and must be of type boolean. Init can be
any of the following: nothing, a local variable declaration, or an expression. Init can also be
a series of local variable declarations and expressions separated by commas. Update can be
omitted, can be an expression, or can be a series of expressions separated by commas.
Most often, a forstatement is written such that Init initializes a loop control variable and
Update increments or decrements the loop control variable. Here are two loops that execute
the same number of times (50):
for (loopCount = 1; loopCount <= 50; loopCount++)
.
.
.
for (loopCount = 50; loopCount >= 1; loopCount--)
.
.
.
Just likewhileloops,doandforloops may be nested. For example, the nestedforstructure
for (lastNum = 1; lastNum <= 7; lastNum++)
{
for (numToPrint = 1; numToPrint <= lastNum; numToPrint++)
outFile.print("" + numToPrint);
outFile.println();
}
prints the following triangle of numbers:
1
12
123
1234
12345
123456
1234567
Although forstatements are used primarily for count-controlled loops, Java allows you
to write any whileloop by using a forstatement. To use forloops intelligently, you should
know the following facts:
for (Init ; Expression ; Update )
Statement
For-Statement
やまだぃちぅ
(やまだぃちぅ)
#1