Java Reference
In-Depth Information
12 * 11 = 132
12 * 12 = 144
Exercise 2 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”>
var timesTable = 12;
var timesBy;
for (timesBy = 1; timesBy < 13; timesBy++)
{
document.write(timesTable + “ * “ + timesBy + “ = “ + timesBy * timesTable +
“<br />”);
}
</script>
</body>
</html>
Save this as ch3_q2.htm .
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 concat-
enation 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.
Exercise 3 Question
Change the code of Question 2 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 3 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