8
JavaScript: Control
Statements II, Solutions
Who can control his fate?
—William ShakespeareNot everything that can be
counted counts, and not every
thing that counts can be
counted.
—Albert Einstein
Self-Review Exercises
8.1
State whether each of the
following is true or false. If false,
ex-plain why.
a) The
defaultcase is
re-quired in the
switchselection statement.
O b j e c t i v e s
In this chapter you’ll:
■
Learn the essentials of
counter-controlled repetition
■Use the
forand
do
…
while
repetition statements to
execute statements in a
program repeatedly.
■Perform multiple selection
using the
switch
selection
statement.
■
Use the
break
and
continue
program-control
statements
■
Use the logical operators to
make decisions.
To Program 5th Edition Deitel
Download full at:
https://testbankdata.com/download/solutions-manual-internet-world-wide-web-program-5th-edition-deit
el/
ANS:
False. The
defaultcase is optional. If no
defaultaction is needed, then there’s no
need for a default case.
b) The
breakstatement is required in the last case of a
switchselection statement.
ANS:
False. The
breakstatement is used to exit the
switchselection statement. The
breakstatement is not required for the last
casein a
switchselection statement.
c) The expression
( x > y && a < b )is true if either
x > yis true or
a < bis true.
ANS:
False. Both of the relational expressions must be true for the entire expression to be
true when using the
&&operator.
d) An expression containing the
||operator is true if either or both of its operands is true.
ANS:
True.
8.2
Write a JavaScript statement or a set of statements to accomplish each of the following tasks:
a) Sum the odd integers between 1 and 99. Use a
forstructure. Assume that the variables
sum
and
counthave been declared.
ANS: sum = 0;
for
( count = 1; count <= 99; count += 2 ) sum += count;b) Calculate the value of 2.5 raised to the power of 3. Use the
powmethod.
ANS: Math.pow( 2
.
5, 3 )c) Print the integers from 1 to 20 by using a
whileloop and the counter variable
x. Assume
that the variable
xhas been declared, but not initialized. Print only five integers per line.
[Hint: Use the calculation
x % 5. When the value of this expression is
0, start a new
paragraph in the HTML5 document.]
ANS: x = 1; document.writeln( "<p>" ); for ( x = 1; x <= 20; x++ ) { document.write( x + " " ); if ( x % 5 == 0 ) document.write( "</p><p>" ); } document.writeln( "</p>" );
d) Repeat Exercise 8.2 (c), but using a
forstatement.
ANS: document.writeln( "<p>" ); for ( x = 1; x <= 20; x++ ) { document.write( x + " " ); if ( x % 5 == 0 ) document.write( "</p><p>" ); } document.writeln( "</p>" );
8.3
Find the error in each of the following code segments, and explain how to correct it:
a) x = 1;while ( x <= 10 ); ++x;
}
ANS:
Error: The semicolon after the
whileheader causes an infinite loop, and there’s a
missing left brace.
Correction: Replace the semicolon with a
{, or remove both the
;and the
}.
b)
switch ( n ){
case 1:
document.writeln( "The number is 1" ); case 2:
document.writeln( "The number is 2" ); break;
default:
document.writeln( "The number is not 1 or 2" ); break;
}
ANS:
Error: Missing
breakstatement in the statements for the first case.
Correction: Add a
breakstatement at the end of the statements for the first case. Note
that this missing statement is not necessarily an error if you want the statement of
case 2:to execute every time the
case 1:statement executes.
c) The following code should print the values from 1 to 10:
n = 1;while ( n < 10 )
document.writeln( n++ );
ANS:
Error: Improper relational operator used in the
whilerepetition-continuation
condi-tion.
Correction: Use
<=rather than
<, or change
10to
11.
Exercises
8.4
Find the error in each of the following segments of code [Note: There may be more than
one error]:
a)
For ( x = 100, x >= 1, ++x ) document.writeln( x );ANS:
Error:
Forshould be lowercase to be recognized, and the statements need to be
sep-arated by semicolons. Also, this code will result in an infinite loop, since
++xwill
con-tinue to increment
x, and it will never fail to fulfill the condition
x >= 1.
Correction: Change
Forto lowercase, replace every
,with
;and change
++xto
--xor switch the locations of the
100and the
1 and the >=to a
<=.
b) The following code should print whether the integer value is odd or even:
switch ( value % 2 ){
case 0:
document.writeln( "Even integer" ); case 1:
document.writeln( "Odd integer" ); }
ANS:
Error: There should be
breakstatements for eacb case. Currently, both statements
will be executed for
case 0.
Correction: Add a
breakstatement after the content in each
case.
c) The following code should output the odd integers from 19 to 1:
for ( x = 19; x >= 1; x += 2 ) document.writeln( x );
ANS:
Error: The code results in an infinite loop, since
xwill never be less than 1 if it starts
at 19 and always increments.
Correction: The
+=statement should be replaced with
-=.
d) The following code should output the even integers from 2 to 100:
counter = 2; do
{
counter += 2;
} While ( counter < 100 );
ANS:
Error: The
Whilestatement should be lowercase, and the statement inside the
whiledoes not include the final case (where
counter = 100).
Correction: Change
whileto lowercase, and make the conditional statement
counter <= 100or
counter < 101.
8.5
What does the following script do?
ANS:
8.6
Write a script that finds the smallest of several non-negative integers. Assume that the first
value read specifies the number of values to be input from the user.
1 <!DOCTYPE html>
2
3 <!-- Exercise 8.5: ex08_05.html --> 4 <html>
5 <head>
6 <meta charset = "utf-8">
7 <title>Mystery</title> 8 <script>
9
10 document.writeln( "<table>" );
11
12 for ( var i = 1; i <= 7; i++ )
13 { 14 document.writeln( "<tr>" ); 15 16 for ( var j = 1; j <= 5; j++ ) 17 document.writeln( "<td>(" + i + ", " + j + ")</td>" ); 18 19 document.writeln( "</tr>" ); 20 } // end for 21 22 document.writeln( "</table>" ); 23 24 </script> 25 </head><body /> 26 </html>
ANS:
1
<!DOCTYPE html>2
3
<!-- Exercise 8.6 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<title>Solution 8.6</title>8
<script>9
10
var i;11
var input;12
var amount;13
var current;14
var smallest;15
16
input = parseInt( window.prompt( "How many numbers?", "0" ) );17
amount = parseInt( input );18
19
if ( input !== 0 )20
{21
input = window.prompt( "Enter first integer:", "0" );22
smallest = parseInt( input );23
document.writeln( "Number entered: " + smallest );24
} // end if25
26
for ( i = 2 ; i <= amount ; i++ )27
{28
input = window.prompt( "Enter next integer", "0" );29
current = parseInt( input );30
document.writeln( "<br />Number entered: " + current );31
32
if ( current < smallest )33
smallest = current;34
} // end for35
document.writeln( "<p>Smallest number is: " +36
smallest + "</p>" );37
38
</script>39
</head><body></body>40
</html>8.7
Write a script that calculates the product of the odd integers from 1 to 15 and outputs
HTML5 text that displays the results.
ANS:
1
<!DOCTYPE html>2
3
<!-- Exercise 8.7 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<title>Solution 8.7</title>8.8
Modify the compound interest program in Fig. 8.6 to repeat its steps for interest rates of 5,
6, 7, 8, 9 and 10 percent. Use a
forstatement to vary the interest rate. Use a separate table for each
rate.
ANS:8
<script>9
10
var result = 1;11
12
for ( var i = 1; i <= 15; i += 2 )13
result *= i;14
15
document.writeln( "<h2>Solution 8.7</h2>" );16
document.writeln( "Result = " + result );17
18
</script>19
</head><body></body>20
</html>1
<!DOCTYPE html>2
3
<!-- Exercise 8.8 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<title>Solution 8.8</title>8
<style type = "text/css">9
table { width: 300px;10
border-collapse: collapse;11
background-color: lightblue;12
margin: 10px;}13
table, td, th { border: 1px solid black;14
padding: 4px; }15
th { text-align: left;16
color: white;17
background-color: darkblue; }18
tr.oddrow { background-color: white; }19
</style>20
<script>21
22
var principal = 1000.0;24
for ( var interestRate = 5; interestRate <= 10; interestRate++ )25
{26
document.writeln( "<table>" );27
document.writeln( "<tr><th>Year</th>" );28
document.writeln( "<th>Amount on deposit</th>" );29
document.writeln( "<th>Interest Rate</th></tr>" );30
31
var rate = interestRate / 100.0;32
33
for ( var year = 1; year <= 10; year++ )34
{35
var amount = principal * Math.pow( 1.0 + rate, year );36
37
if ( year % 2 !== 0 )38
document.writeln( "<tr class='oddrow'><td>" + year +39
"</td><td>" + amount.toFixed( 2 ) + "</td><td>" +40
rate + "</td></tr>" );41
else42
document.writeln( "<tr><td>" + year +43
"</td><td>" + amount.toFixed( 2 ) + "</td><td>" +44
rate + "</td></tr>" );45
} // end for46
47
document.writeln( "</table>" );48
} // end for49
50
</script>51
</head><body></body>52
</html>8.9
One interesting application of computers is drawing graphs and bar charts (sometimes
called histograms). Write a script that reads five numbers between 1 and 30. For each number read,
output HTML5 text that displays a line containing that number of adjacent asterisks. For example,
if your program reads the number 7, it should output HTML5 text that displays *******.
ANS:
1
<!DOCTYPE html>2
3
<!-- Exercise 8.9 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<title>Solution 8.9</title>8
<script>9
10
var input;11
var number;12
13
for ( var i = 1; i <= 5; ++i )14
{15
input = window.prompt( "Enter a number: ", "0" );16
number = parseInt( input );17
18
while ( number < 1 || number > 30 )19
{20
input = window.prompt( "Input not in range. " +21
"Enter a number: ", "0" );22
number = parseInt( input );23
}24
25
document.writeln( "<p>" );26
27
for ( var stars = 1; stars <= number; ++stars )28
document.write( "*" );29
30
document.writeln( "</p>" );31
} // end for32
33
</script>34
</head><body></body>35
</html>8.10
("The Twelve Days of Christmas” Song) Write a script that uses repetition and a
switchstruc-tures to print the song “The Twelve Days of Christmas.” You can find the words at the site
www.santas.net/twelvedaysofchristmas.htm ANS:1
<!DOCTYPE html>2
3
<!-- Exercise 8.10 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<title>Solution 8.10</title>8
<style type = "text/css">9
p { margin-top: 0;10
margin-bottom: 0; }11
p.firstline { margin-top: 20px; }12
</style>13
<script>14
15
document.writeln( "<h1>The Twelve Days of Christmas</h1>" );16
17
for ( var day = 1; day <= 12; ++day )18
{19
document.write( "<p class='firstline'>On the " );20
21
switch ( day )22
{23
case 1:24
document.write( "first" );25
break;26
case 2:27
document.write( "second" );28
break;29
case 3:30
document.write( "third" );31
break;32
case 4:33
document.write( "fourth" );34
break;35
case 5:36
document.write( "fifth" );37
break;38
case 6:39
document.write( "sixth" );40
break;41
case 7:42
document.write( "seventh" );43
break;44
case 8:45
document.write( "eighth" );46
break;47
case 9:48
document.write( "ninth" );49
break;50
case 10:51
document.write( "tenth" );52
break;53
case 11:54
document.write( "eleventh" );55
break;56
case 12:57
document.write( "twelfth" );58
break;59
} // end switch60
61
document.writeln(62
" day of Christmas,</p><p>my true love gave to me:</p>" );63
64
// display remainder of verse65
switch ( day )66
{67
case 12:68
document.writeln( "<p>Twelve drummers drumming,</p>" );69
70
case 11:71
document.writeln( "<p>Eleven pipers piping,</p>" );72
73
case 10:74
document.writeln( "<p>Ten lords-a-leaping,</p>" );75
76
case 9:77
document.writeln( "<p>Nine ladies dancing,</p>" );78
79
case 8:80
document.writeln( "<p>Eight maids-a-milking,</p>" );81
82
case 7:83
document.writeln( "<p>Seven swans-a-swimming,</p>" );84
85
case 6:87
88
case 5:89
document.writeln( "<p>Five golden rings.</p>" );90
91
case 4:92
document.writeln( "<p>Four calling birds,</p>" );93
94
case 3:95
document.writeln( "<p>Three French hens,</p>" );96
97
case 2:98
document.writeln( "<p>Two turtle doves, and</p>" );99
100
case 1:101
document.writeln( "<p>a Partridge in a pear tree.</p>");102
} // end switch103
} // end for104
//-->105
</script>106
</head><body></body>107
</html>8.11
A mail-order house sells five different products whose retail prices are as follows: product 1,
$2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49; and product 5, $6.87. Write a script
that reads a series of pairs of numbers as follows:
a) Product number
b) Quantity sold for one day
Your program should use a
switchstatement to help determine the retail price for each product
and should calculate and output HTML5 that displays the total retail value of all the products sold
last week. Use a
promptdialog to obtain the product number and quantity from the user. Use a
sen-tinel-controlled loop to determine when the program should stop looping and display the final
results.
ANS:1
<!DOCTYPE html>2
3
<!-- Exercise 8.11 Solution -->4
<html>5
<head>6
<meta charset = "utf-8">7
<style type = "text/css">8
table { width: 100% }9
th { text-align: left }10
</style>11
<title>Solution 8.11</title>12
<script>13
14
var product1 = 0;15
var product2 = 0;16
var product3 = 0;17
var product4 = 0;18
var product5 = 0;19
var inputString;20
var productId = 1;21
22
while ( productId != 0 )23
{24
inputString = window.prompt(25
"Enter product number ( 1-5 ) ( 0 to stop ):" );26
productId = parseInt( inputString );27
28
if ( productId >= 1 && productId <= 5 )29
{30
inputString = window.prompt(31
"Enter quantity sold:" );32
var quantity = parseInt( inputString );33
34
switch ( productId )35
{36
case 1:37
product1 += quantity * 2.98;38
break;39
case 2:40
product2 += quantity * 4.50;41
break;42
case 3:43
product3 += quantity * 9.98;44
break;45
case 4:46
product4 += quantity * 4.49;47
break;48
case 5:49
product5 += quantity * 6.87;50
break;51
} // end switch52
} // end if53
else if ( productId != 0 )54
{55
window.alert(56
"Product number must be between 1 and 5 or "57
+ "0 to stop" );58
} //end else if59
} // end while60
61
document.writeln( "<h2>Product Totals</h2>" );62
document.writeln( "<table border = '1'>" );63
document.writeln( "<tr><th>Product #</th>" );64
document.writeln( "<th>Total Sales</th></tr>" );65
document.writeln( "<tr><td> Product 1 </td><td>"66
+ product1 + "</td>" + "<tr><td> Product 2 </td><td>"67
+ product2 + "</td></tr>" + "<tr><td> Product 3 </td><td>"68
+ product3 + "</td></tr>" + "<tr><td> Product 4 </td><td>"69
+ product4 + "</td></tr>" + "<tr><td> Product 5 </td><td>"70
+ product5 + "</td></tr></table>" );71
72
</script>73
</head><body></body>74
</html>8.12
Assume
i = 1,
j = 2,
k = 3and
m = 2. What does each of the following statements print?
Are the parentheses necessary in each case?
a)
document.writeln( i == 1 ); ANS: trueb)
document.writeln( j == 3 ); ANS: falsec)
document.writeln( i >= 1 && j < 4 ); ANS: trued)
document.writeln( m <= 99 & k < m ); ANS: false[Note: The
&in part (d) should be
&&.]
e)
document.writeln( j >= i || k == m ); ANS: truef)
document.writeln( k + m < j || 3 - j >= k ); ANS: false[Note: The
|in part (f) should be
||.]
g)
document.writeln( !( k > m ) );8.13
Given the following
switchstatement:
What values are assigned to
xwhen
khas values of 1, 2, 3, 4 and 10?
ANS: x