Chapter 8

Question 8.1

Question 8.2

Write a JavaScript statement or a set of statements to accomplish each of the following tasks:

  1. a) sum = 0; for ( count = 1; count <= 99; count += 2 ) sum += count;
  2. b) Math.pow( 2.5, 3 )
  3. c) x = 1; document.writeln( "<p>" ); while ( x <= 20 ) { document.write( x + " " ); if ( x % 5 == 0 ) document.write( "</p><p>" ); ++x; }
  4. d) document.writeln( "<p>" ); for ( x = 1; x <= 20; x++ ) { document.write( x + " " ); if ( x % 5 == 0 ) document.write( "</p><p>" );} document.writeln( "</p>" );

Question 8.3

  1. a) Error: The semicolon after the while header causes an infinite loop, and there’s a missing left brace.
    Correction: Replace the semicolon by a {, or remove both the ; and the }.
  2. b) Error: Missing break statement in the statements for the first case.
    Corre-ction: 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 you want the statement of case 2: to execute every time the case 1: statement executes.
  3. c) Error: Improper relational operator used in the while continuation condition. Correction: Use <= rather than <, or change 10 to 11.

Question 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 );

Errors: simicolon should be used in the condition of the for loop instead of copmma. The f in for is capitalised. The for loop condition will never be lessthen or equal too one, x should decrease after every call x- - instead of x + + .

b) The following code should print whether integer value is odd or even;


switch ( value % 2 ){
case 0:
document.writeln( "Even integer" );
case 1:
document.writeln( "Odd integer" );

}

Errors: none of the swithch statements have a break; no default case.

c) The following code should output the odd integers from 19 to 1:

for ( x = 19; x >= 1; x += 2 )
document.writeln( x );

Error: The for statement will never terminate x should be decreased instead of increased, x = - 2.

d) The following code should output the even integers from 2 to 100;

counter = 2;
do{
document.writeln( counter );
counter += 2;
} While ( counter < 100 );

Error: While loop counter should be counter = 100 so 100 can print.

Question 8.5

8.5 What does the following script do?

Question 8.5

Question 8.6

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.

Java 8.6 answer


8.7 Write a script that calculates the product of the odd integers from 1 to 15 then outputs HTML5 text that displays the results.

Java 8.7 answer