Java Reference
In-Depth Information
Converting a Series of Fahrenheit Values
trY it out
Let's change the temperature converter so that it converts a series of values, stored in an array, from
Fahrenheit to centigrade. You will be using the
for
statement to go through each element of the array.
Type the following code and save it as
ch3 _ example4.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3, Example 4</title>
</head>
<body>
<script>
var degFahren = [212, 32, -459.15];
var degCent = [];
var loopCounter;
for (loopCounter = 0; loopCounter <= 2; loopCounter++) {
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}
for (loopCounter = 2; loopCounter >= 0; loopCounter
−−
) {
document.write("Value " + loopCounter +
" was " + degFahren[loopCounter] +
" degrees Fahrenheit");
document.write(" which is " + degCent[loopCounter] +
" degrees centigrade<br />");
}
</script>
</body>
</html>
On loading this into your browser, you'll see a series of three lines in the page, containing the results of
converting your array of Fahrenheit values into centigrade (as shown in Figure 3-11).
The first task is to declare the variables you are going to use. First, you declare and initialize
degFahren
to contain an array of three values:
212
,
32
, and
-459.15
. Next, you declare
degCent
as an empty array.
Finally, you declare
loopCounter
and will use it to keep track of which array index you are accessing
during your looping:
var degFahren = [212, 32, -459.15];
var degCent = [];
var loopCounter;
Following this comes your first
for
loop:
for (loopCounter = 0; loopCounter <= 2; loopCounter++) {
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
}