Java Reference
In-Depth Information
Thegeneralformoftheforloopinstructionisshownin Figure10-2 .
for keyword
initializing element
test element
update element
for(var = 0; var < 5; var++)
{
// processing statements
}
Figure10-2ElementsoftheforLoopConstruct
Wecanusetheforloopinthefollowingcodefragmentforcalculating
thefactorialaccordingtotheflowchartin Figure10-1 .
int number = 5;
// Factorial to be calculated
int facProd, curFactor;
// Local variables
// Initialization step
facProd = number; // Initialize operational variable
for (curFactor = number - 1; curFactor > 1; curFactor--)
facProd = curFactor * facProd;
// Done
System.out.println("Factorial is: ", + facProd);
Note that the expression
for(curFactor = number - 1; curFactor > 1; curFactor --)
contains the loop expression and that it includes elements from steps 1, 2,
and 3. The first statement (curFactor = number - 1) sets the initial value of
the loop variable. The second statement (curFactor > 1) contains the test
conditionand determinesiftheloopcontinuesorifitends.Thethirdstate-
ment(curFactor--)diminishestheloopvariableby1duringeachiteration.
Note that while the for loop expression does not end in a semicolon, it
does contain semicolon symbols. In the case of the for loop, the semico-
lon symbol is used to separate the initialization, test, and update elements
of the loop. This action of the semicolon symbol allows the use of multi-
ple statements in each element of the loop expression, as in the following
case:
unsigned int x;
unsigned int y;
for(x = 0,y=5;x<5;x++, y--)
System.out.println("x is:"+x,"yis:"+y);
 
Search WWH ::




Custom Search