Java Reference
In-Depth Information
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
writeTimesTable(4, 4, 9);
</script>
</body>
</html>
Save this as ch4 _ question1.html .
You've declared your function, calling it writeTimesTable() , and given it three parameters. The
first 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 modified 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 2 Question
Modify the code of Question 1 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 2 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
Search WWH ::




Custom Search