Java Reference
In-Depth Information
exercise 2 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3: Question 2</title>
</head>
<body>
<script>
var timesTable = 12;
for (var timesBy = 1; timesBy < 13; timesBy++) {
document.write(timesTable + " * " +
timesBy + " = " +
timesBy * timesTable + "<br />");
}
</script>
</body>
</html>
Save this as ch3 _ question2.html .
You use a for loop to calculate from 1 * 12 up to 12 * 12 . The results are written to the page
with document.write() . What's important to note here is the effect of the order of precedence; the
concatenation operator (the + ) has a lower order of precedence than the multiplication operator, * .
This means that the timesBy * timesTable is done before the concatenation, which is the result
you want. If this were not the case, you'd have to put the calculation in parentheses to raise its order
of precedence.
Chapter 4
exercise 1 Question
Change the code of Question 2 from Chapter 3 so that it's a function that takes as parameters the
times table required and the values at which it should start and end. For example, you might try the
four times table displayed starting with 4 * 4 and ending at 4 * 9 .
exercise 1 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 1</title>
</head>
<body>
<script>
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
Search WWH ::




Custom Search