Java Reference
In-Depth Information
figure 3-11  
In the first line, you start by initializing the loopCounter to 0 . Then the for loop's test condition,
loopCounter <= 2 , is checked. If this condition is true , the loop executes for the first time. After the
code inside the curly braces has executed, the incrementing part of the for loop, loopCounter++ , will
be executed, and then the test condition will be re‐evaluated. If it's still true , another execution of the
loop code is performed. This continues until the for loop's test condition evaluates to false , at which
point looping will end, and the first statement after the closing curly brace will be executed.
The code inside the curly braces is the equation you saw in earlier examples, only this time you are
placing its result into the degCent array, with the index being the value of loopCounter .
In the second for loop, you write the results contained in the degCent array to the screen:
for (loopCounter = 2; loopCounter >= 0; loopCounter −− ) {
document.write("Value " + loopCounter +
" was " + degFahren[loopCounter] +
" degrees Fahrenheit");
document.write(" which is " + degCent[loopCounter] +
" degrees centigrade<br />");
}
This time you're counting down from 2 to 0 . The variable loopCounter is initialized to 2 , and the loop
condition remains true until loopCounter is less than 0 . This time loopCounter is actually decremented
each time rather than incremented, by means of loopCounter −− . Again, loopCounter is serving a dual
purpose: It keeps count of how many loops you have done and also provides the index position in the array.
Note In these examples, you've used whole numbers in your loops. However,
there is no reason why you can't use fractional numbers, although it's much
less common to do so.
Search WWH ::




Custom Search