8.1 State whether each of the following is true or false. If false, explain why.
- The default case is required in the switch selection statement. False. The default case is optional. If no default action is needed, then there is no need for a default case.
- The break statement is required in the last case of a switch selection statement. False. The break statement is used to exit the switch statement. The break statement is not required for the last case in a switch statement.
- The expression ( x > y && a < b ) is true if either x > y is true or a < b is true. False. Both of the relational expressions must be true in order for the entire expression to be true when using the && operator.
- An expression containing the || operator is true if either or both of its operands is true. True.
8.2 Write a JavaScript statement or a set of statements to accomplish each of the following tasks:
- Sum the odd integers between 1 and 99. Use a for statement. Assume that the variables sum and count have been declared.
sum = 0;
for ( count = 1; count <= 99; count += 2 )
sum += count;
- Calculate the value of 2.5 raised to the power of 3. Use the pow method.
Math.pow( 2.5, 3 );
- Print the integers from 1 to 20 by using a while loop and the counter variable x. Assume that the variable x has 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, use document.write( "<br />" ) to output a line break in the XHTML document.]
x = 1;
while ( x <= 20 )
{
document.write( x + " " );
if ( x % 5 == 0 )
document.write( "<br />" );
++x;
}
- Repeat Exercise 8.2(c), but using a for statement.
for ( x = 1; x <= 20; x++ )
{
document.write( x + " " );
if ( x % 5 == 0 )
document.write( "<br />" );
}
or
for ( x = 1; x <= 20; x++ )
{
if ( x % 5 == 0 )
document.write( "<br />" );
else
document.write( x + " " );
}
8.3 Find the error in each of the following code segments, and explain how to correct it:
Error: The semicolon after the while header causes an infinite loop, and there is a missing left brace. Correction: Replace the semicolon by a {, or remove both the ; and the }.
x = 1;
while ( x <= 10 )
{
++x;
}
Error: Using a floating-point number to control a for repetition statement may not work, because floating-point numbers are represented approximately by most computers. Correction: Use an integer, and perform the proper calculation to get the values you desire.
for ( y = 1; y != 10; y++ )
document.writeln( ( y / 10 ) + " " );
Error: Missing break statement in the statements for the first case. Correction: Add a break statement at the end of the statements for the first case. Note that this missing statement is not necessarily an error if the programmer wants the statement of case 2: to execute every time the case 1: statement executes.
switch ( n )
{
case 1:
document.writeln( "The number is 1" );
break;
case 2:
document.writeln( "The number is 2" );
break;
default:
document.writeln( "The number is not 1 or 2" );
break;
}
Error: Improper relational operator used in the while continuation condition. Correction: Use <= rather than <, or change 10 to 11.
n = 1;
while ( n <= 10 )
document.writeln( n++ );
8.4 Find the error in each of the following segments of code. [Note: There may be more than one error.]
Error: The for statement creates an infinite loop, should not contain commas, and "For" should not be capital. Correction: The variable x should be decremented, not incremented, semicolons should be used, and "For" should be "for".
for ( x = 100; x >= 1; x−− )
document.writeln( x );
Error: The switch cases have no break statements. Correction: Add a break to each switch case.
switch ( value % 2 )
{
case 0:
document.writeln( "Even integer" );
break;
case 1:
document.writeln( "Odd integer" );
break;
}
Error: The for statement creates an infinite loop. Correction: The variable x should be decremented, not incremented.
for ( x = 19; x >= 1; x -= 2 )
document.writeln( x );
Error: The while statement should not have a capital w and won't output 100. Correction: Change "While" to "while" and counter <= 100.
counter = 2;
do {
document.writeln( counter );
counter += 2;
} while ( counter <= 100 );
8.5 What does the following script do?
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.
8.7 Write a script that calculates the product of the odd integers from 1 to 15 then outputs XHTML text that displays the results.
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 for statement to vary the interest rate. Use a separate table for each rate.
8.9 Write a script that outputs XHTML to display the given patterns separately, one below the other. Use for statements to generate the patterns. All asterisks (*) should be printed by a single statement of the form document.write( "*" ); (this causes the asterisks to print side by side). A statement of the form document.writeln( "<br />" ); can be used to position the next line. A statement of the form document.write( " "); can be used to display a space (needed for the last two patterns). There should be no other output statements in the program. [Hint: The last two patterns require that each line begin with an approiate number of blanks. You may need to use the XHTML <pre></pre> tags.]
8.10 One interesting application of computers is the drawing of graphs and bar charts (sometimes called histograms). Write a script that reads five numbers between 1 and 30. For each number read, output XHTML text that displays a line containing the same number of adjacent asterisks. For example, if your program reads the number 7, it should output XHTML text that displays *******.
8.11 ("The Twelve Days of Christmas Song") Write a script that uses repetition and a switch structure to print the song "The Twelve Days of Christmas." You can find the words at the site www.santas.net/twelvedaysofchristmas.htm
8.12 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:
- Product number
- Quantity sold for the day
Your program should use a switch statement to determine each product's retail price and should calculate and output XHTML that displays the total retail value of all the products sold last week. Use a prompt dialog to obtain the product number and quantity from the user. Use a sentinel-controlled loop to determine when the program should stop looping and display the final results.
8.13 Assume that i = 1, j = 2, k = 3 and m = 2. What does each of the given statements print? Are the parentheses necessary in each case?
- document.writeln( i == 1 ); true - parentheses necessary for writeln statement, not logical operations
- document.writeln( j == 3 ); false - parentheses necessary for writeln statement, not logical operations
- document.writeln( i >= 1 && j < 4 ); true - parentheses necessary for writeln statement, not logical operations
- document.writeln( m <= 99 && k < m ); false - parentheses necessary for writeln statement, not logical operations
- document.writeln( j >= i || k == m ); true - parentheses necessary for writeln statement, not logical operations
- document.writeln( k + m < j || 3 - j >= k ); false - parentheses necessary for writeln statement, not logical operations
- document.writeln( !( k > m ) ); false - parentheses necessary for writeln statement and logical operations
8.14 Modify Exercise 8.9 to combine your code from the four separate triangles of asterisks into a single script that prints all four patterns side by side, making clever use of nested for statements.
8.15 (De Morgan's Laws) In this chapter, we have discussed the logical operators &&, ||, and !. De Morgan's Laws can sometimes make it more convenient for us to express a logical expression. These laws state that the expression !(condition1 && condition2) is logically equivalent to the expression (!condition1 || !condition2). Also, the expression !(condition1 || condition2) is logically equivalent to the expression (!condition1 && !condition2). Use De Morgan's Laws to write equivalent expressions for each of the following, then write a program to show that the original expression and the new expression are equivalent in each case:
- !( x < 5 ) && !( y >= 7 ) Equivalent to: !( x < 5 || y >= 7 ) 8.15a Example
- !( a == b ) || !( g != 5 ) Equivalent to: !( a == b && g != 5 ) 8.15b Example
- !( ( x <= 8 ) && ( y > 4 ) ) Equivalent to: !( x <= 8 ) || !( y > 4 ) 8.15c Example
- !( ( i > 4 ) || ( j <= 6 ) ) Equivalent to: !( i > 4 ) && !( j <= 6 ) 8.15d Example
8.16 Write a script that prints the following diamond shape:
You may use output statements that print a single asterisk (*), a single space or a single newline character. Maximize your use of repetition (with nested for statements), and minimize the number of output statements.
8.17 Modify the program you wrote in Exercise 8.16 to read an odd number in the range 1 to 19. This number specifies the number of rows in the diamond. Your program should then display a diamond shape of the approiate size.
8.18 A criticism of the break statement and the continue statement is that each is unstructured. Actually, break statements and contine statements can always be replaced by structured statements, although coding the replacement can be awkward. Describe in general how you would remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement "jumps out of" a loop from the body of that loop. The other way to leave is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates "early exit because of a 'break' condition."] Use the technique you develop here to remove the break statement from the program in Fig. 8.11.
The break condition can be defined in the loop as well as the normal continuation condition. Checking for the break condition rather than altering the variable to fail the continuation retains the expected value of the variable.
8.19 What does the following script do?
8.20 Describe in general how you would remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the technique you develop to remove the continue statement from the program in Fig. 8.12
An "if" statement can be used to test for the continue condition. If the continue condition is not met perform the remaining operations.
8.21 Given the following switch statement:
What values are assigned to x when k has values of 1, 2, 3, 4 and 10?
when k == 1, x = 1
when k == 2, x = 3
when k == 3, x = 4
when k == 4, x = 3
when k == 10, x = 30