Java Reference
In-Depth Information
You can also leave either the initialization or increment blank in a for loop. In this case, you would
need to specify the variable before the for loop or the increment during the for loop. Following are
two examples that function the same as the previous example, but with a slightly different syntax.
int[] sales2014 = {500,720,515,377,400,435,510,1010,894,765,992,1125};
int[] staff2014 = {7,5,5,5,5,6,6,7,7,8,9,9};
int[] salesPerStaff = new int[12];
int totalSales2014 = 0;
int i = 0; //specify initialization variable here, not before termination
for ( ; i<sales2014.length; i++){
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
}
int[] sales2014 = {500,720,515,377,400,435,510,1010,894,765,992,1125};
int[] staff2014 = {7,5,5,5,5,6,6,7,7,8,9,9};
int[] salesPerStaff = new int[12];
int totalSales2014 = 0;
for (int i=0; i<sales2014.length; ){
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
i = i + 1; //specify increment here, not after termination
}
It is important to keep your termination condition and increment direction in mind when you are set-
ting up a for loop. You could unintentionally create an infinite loop by having these misaligned. For
example, imagine the following for loop: for (int i = 5; i > 0; i++) . Your loop will continue to
repeat indefinitely. The starting value for i is 5 , which is greater than 0 , and the value of i will continue
increasing as you loop, so it will always remain greater than 0 . In general, a termination condition using
> will have an increment using -- , and a termination condition using < will have an increment using ++ .
Another consideration is how your iterator may be altered within the for loop. It is possible to reas-
sign the value of your iterator as part of the loop, instead of or in addition to the increment expres-
sion. Consider adding a line to the example.
int[] sales2014 = {500,720,515,377,400,435,510,1010,894,765,992,1125};
int[] staff2014 = {7,5,5,5,5,6,6,7,7,8,9,9};
int[] salesPerStaff = new int[12];
int totalSales2014 = 0;
for (int i=0; i<sales2014.length; i++){
i = i*2; //this line is added
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
}
Here, the value of i is changed as part of the increment and also within the loop. So the loop will be
processed in the following way:
1. Start at the beginning of the for loop. i =0 and 0 < 12, so the loop is entered.
2. i = i *2 or i = 0*2 = 0, so the statements are evaluated on the 0 (first) element of each array.
Search WWH ::




Custom Search