Where the iteration is over a range of values, a for loop is a more compact alternative to a while or do while loop. The syntax is
for(initialization expression; test expression; increment expression)
{
one or more statements;
}
The initialization expression is executed once at the beginning of the first loop iteration. The increment expression is executed at the end of every loop iteration. The test expression is evaluated at the beginning of each loop iteration. If the test expression evaluates to false, the for loop is terminated; if it evaluates to true, another iteration of the loop is executed. Like a while loop, it is possible that the for loop may not be executed for a single iteration.
For example
for (i = 0; i < intArray.length; i++)
{
intArray[i] = i+1;
}
Note that initialization, i=0; increment, i++; and test expression,i < intArray.length all occur on a single line. Any of the three parts of a for loop can be omitted, but the semicolons must remain. If all three parts are omitted, we have an infinite for loop, as follows:
for (;;) {
...
}
Within the for loop, there will be some means, such as a break statement, to end the looping.
3.3.3 Using for Loop in Java
Tags
# for loop
# Java Flow Controls
Share This
Java Flow Controls
Labels:
for loop,
Java Flow Controls
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment