Java Reference
In-Depth Information
{
for (;timesByStart <= timesByEnd; timesByStart++)
{
document.write(timesTable + “ * “ + timesByStart + “ = “ +
timesByStart * timesTable + “<br />”);
}
}
writeTimesTable(4,4,9);
</script>
</body>
</html>
Save this as ch3_q3.htm .
You've declared your function, calling it writeTimesTable() , and given it three parameters. The fi rst
is the times table you want to write, the second is the start point, and the third is the number it should
go up to.
You've mo d i fi ed your for loop. First you don't need to initialize any variables, so the initialization part
is left blank — you still need to put a semicolon in, but there's no code before it. The for loop continues
while the timesByStart parameter is less than or equal to the timesByEnd parameter. You can see
that, as with a variable, you can modify parameters — in this case, timesByStart is incremented by
one for each iteration through the loop.
The code to display the times table is much the same. For the function's code to be executed, you now
actually need to call it, which you do in the line
writeTimesTable(4,4,9);
This will write the 4 times table starting at 4 times 4 and ending at 9 times 4.
Exercise 4 Question
Modify the code of Question 3 to request the times table to be displayed from the user; the code should
continue to request and display times tables until the user enters -1 . Additionally, do a check to make
sure that the user is entering a valid number; if the number is not valid, ask the user to re-enter it.
Exercise 4 Solution
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
function writeTimesTable(timesTable, timesByStart, timesByEnd)
Search WWH ::




Custom Search