Chapter 7 Assignments


Home

Section 7.1 Fill in the blanks in each of the following statements

1. All programs can be written in terms of three types of control structures: ________, ________ and ________.
Answer: Sequence, selection and repetition

2. The ________ double-selection statement is used to execute one action when a condition is true and another action when that condition is false.
Answer: If/Else

3. Repeating a set of instructions a specific number of times is called ________ repetition.
Answer: Counter-controlled (or definite)

4. When it is not known in advance how many times a set of statements will be repeated, a(n) ________ (or a(n) ________, ________ or ________) value can be used to terminate the repetition.
Answer: Sentinel, signal, flag or dummy.


Section 7.2

Write four JavaScript statements that each add 1 to variable x, which contains a number.
Answer: • x = x + 1; • x += 1; • ++x; • x++;


Section 7.3 Write JavaScript statements to accomplish each of the following tasks

1. Assign the sum of x and y to z, and increment the value of x by 1 after the calculation. Use only one statement.
Answer: z = x++ + y;

2. Test whether the value of the variable count is greater than 10. If it is, print "Count is greater than 10".
Answer: if ( count > 10 )
                document.writeln( "Count is greater than 10" );

3. Decrement the variable x by 1, then subtract it from the variable total. Use only one statement.
Answer: total -= --x;

4. Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways.
Answer: • q %= divisor;
• q = q % divisor;


Section 7.4 Write a JavaScript statement to accomplish each of the following tasks

1. Declare variables sum and x.
Answer: 1. var sum, x;

2. Assign 1 to variable x.
Answer: x = 1;

3. Assign 0 to variable sum.
Answer: sum = 0;

4. Add variable x to variable sum, and assign the result to variable sum.
Answer: sum += x; or sum = sum + x;

5. Print "The sum is: ", followed by the value of variable sum.
Answer: document.writeln( "The sum is: " + sum );


Section 7.5

Combine the statements that you wrote in Exercise 7.4 into a JavaScript program that calculates and prints the sum of the integers from 1 to 10. Use the while statement to loop through the calculation and increment statements. The loop should terminate when the value of x becomes 11.
Answer: Answer to 7.5


Section 7.6 Determine the value of each variable after the calculation is performed. Assume that, when each statement begins executing, all variables have the integer value 5.

1. product *= x++;
Answer: product = 25, x = 6;

2. quotient /= ++x;
Answer: quotient = 0.833333..., x = 6;


Section 7.7 Identify and correct the errors in each of the following segments of code

1.

            while ( c <= 5 ) {
            product *= c;
            ++c;
        
Answer: Error: Missing the closing right brace of the while body.
Correction: Add closing right brace after the statement ++c;.

2.

            If ( gender == 1 )
                document.writeln( "Woman" );
            else;
                document.writeln( "Man" );
        
Answer: Error: The semicolon after else results in a logic error. The second output statement will always be executed.
Correction: Remove the semicolon after else.


Section 7.8 What is wrong with the following while repetition statement?

            while ( z >= 0 )
                sum += z;
        
Answer: The value of the variable z is never changed in the body of the while statement.
Therefore, if the loop-continuation condition ( z >= 0 ) is true, an infinite loop is created.
To prevent the creation of the infinite loop, z must be decremented so that it eventually becomes less than 0.


Section 7.9 Identify and correct the errors in each of the following segments of code [Note: There may be more than one error in each piece of code]:


1.

            if ( age >= 65 );
                document.writeln( "Age greater than or equal to 65" );
            else
                document.writeln( "Age is less than 65" );
        
Answer: There should not be a semi-colon after the if condition.

2.

            var x = 1, total;
            while ( x <= 10 )
            {
                total += x;
                ++x;
            }
        
Answer: x and total need to be declared on seperate lines.

3.

            var x = 1;
            var total = 0;
                While ( x <= 100 )
                total += x;
             ++x;
        
Answer: x never gets incremented. need to add ++x to the while loop.

4.

          var y = 5;
          while ( y > 0 )
          {
            document.writeln( y );
            ++y;
        
Answer: The while loop will never end.


Section 7.10 What does the following program print?

        1  <?xml version="1.0" encoding="utf-8" ?>
        2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        4
        5  <!-- Exercise 7.10: ex07_10.html -->
        6  <html xmlns="http://www.w3.org/1999/xhtml">
        7     <head><title>Mystery Script</title>
        8        <script type="text/javascript">
        9           <!--
        10           var y;
        11           var x = 1;
        12           var total = 0;
        13
        14           while ( x <= 10 )
        15           {
        16              y = x * x;
        17              document.writeln( y + "<br />" );
        18              total += y;
        19              ++x;
        20           } // end while
        21
        22           document.writeln( "<br />Total is " + total );
        23           // -->
        24        </script>
        25     </head><body></body>
        26  </html>
        
Answer: Answer to 7.10


Section 7.11 Write a JavaScript Program for the following problem.

Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording the number of miles driven and the number of gallons used for each tankful. Develop a JavaScript program that will take as input the miles driven and gallons used (both as integers) for each tankful. The program should calculate and output XHTML text that displays the number of miles per gallon obtained for each tankful and prints the combined number of miles per gallon obtained for all tankfuls up to this point. Use prompt dialogs to obtain the data from the user.
Answer: Answer to 7.11


Section 7.12 Write a JavaScript Program for the following problem.

Develop a JavaScript program that will determine whether a department-store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available:
1. Account number
2. Balance at the beginning of the month
3. Total of all items charged by this customer this month
4. Total of all credits applied to this customer’s account this month
5. Allowed credit limit
The program should input each of these facts from a prompt dialog as an integer, calculate the new balance (= beginning balance + charges – credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit. For customers whose credit limit is exceeded, the program should output XHTML text that displays the message “Credit limit exceeded.”
Answer: Answer to 7.12


Section 7.13 Write a JavaScript Program for the following problem.

A large company pays its salespeople on a commission basis. The salespeople receive $200 per week, plus 9 percent of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9 percent of $5000, or a total of $650. You have been supplied with a list of the items sold by each salesperson. The values of these items are as follows:
Item Value
1 23.99
2 129.75
3 99.95
4 350.89

Develop a program that inputs one salesperson’s items sold for last week, calculates the salesperson’s earnings and outputs XHTML text that displays the salesperson’s earnings. Answer: Answer to 7.13


Section 7.14 Write a JavaScript Program for the following problem.

Develop a JavaScript program that will determine the gross pay for each of three employees. The company pays “straight time” for the first 40 hours worked by each employee and pays “time and a half” for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, determine the employee’s gross pay and output XHTML text that displays the employee’s gross pay. Use prompt dialogs to input the data.
Answer: Answer to 7.14


Section 7.15 Write a JavaScript Program for the following problem.

The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a JavaScript program that inputs a series of 10 single-digit numbers as characters, determines the largest of the numbers and outputs a message that displays the largest number. Your program should use three variables as follows:
1. counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed);
2. number: The current digit input to the program;
3. largest: The largest number found so far.
Answer: Answer to 7.15


Section 7.16 Write a JavaScript Program for the following problem.

Write a JavaScript program that uses looping to print the following table of values. Output the results in an XHTML table. Use CSS to center the data in each column.

AnswerAnswer to 7.16


Section 7.17 Write a JavaScript Program for the following problem.

Using an approach similar to that in Exercise 7.15, find the two largest values among the 10 digits entered. [Note: You may input each number only once.]
Answer: Answer to 7.17


Section 7.18 Write a JavaScript Program for the following problem.

Modify the program in Fig. 7.11 to validate its inputs. For every value input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value.

        1  <?xml version="1.0" encoding="utf-8" ?>
        2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        4
        5  <!-- Fig. 7.11: analysis.html -->
        6  <!-- Examination-results calculation. -->
        7  <html xmlns="http://www.w3.org/1999/xhtml">
        8     <head>
        9        <title>Analysis of Examination Results&/title>
        10        <script type="text/javascript">
        11           v!--
        12           // initializing variables in declarations
        13           var passes = 0; // number of passes
        14           var failures = 0; // number of failures
        15           var student = 1; // student counter
        16           var result; // one exam result
        17
        18           // process 10 students; counter-controlled loop
        19           while ( student <= 10 )
        20           {
        21              result = window.prompt( "Enter result (1=pass,2=fail)", "0" );
        22
        23              if ( result == "1" )
        24                 passes = passes + 1;
        25              else
        26                 failures = failures + 1;
        27
        28              student = student + 1;
        29           } // end while
        30
        31           // termination phase
        32           document.writeln( "<h1>Examination Results</h1>" );
        33           document.writeln(
        34              "Passed: " + passes + "<br />Failed: " + failures );
        35
        36           if ( passes > 8 )
        37              document.writeln( "<br />Raise Tuition" );
        38           // -->
        39        </script>
        40     </head>
        41     <body>
        42    <p>Click Refresh (or Reload) to run the script again</p>
        43  </body>
        44  </html>
    


Answer: Answer to 7.18


Section 7.19 What does the following program print?

    1  <?xml version="1.0" encoding="utf-8" ?>
    2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    4
    5  <!-- Exercise 7.19: ex07_19.html -->
    6  <html xmlns="http://www.w3.org/1999/xhtml">
    7     <head><title>Mystery Script</title>
    8        <script type="text/javascript">
    9           <!--
    10           var count = 1;
    11
    12           while ( count <= 10 )
    13           {
    14              document.writeln(
    15                 count % 2 == 1 ? "****<br />" : "++++++++<br />" );
    16              ++count;
    17           } // end while
    18           // -->
    19        </script>
    20     </head><body></body>
    21  </html>
    

Answer: Answer to 7.19


Section 7.20 What does the following program print?

    1  <?xml version="1.0" encoding="utf-8" ?>
    2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    4
    5  <!-- Exercise 7.20: ex07_20.html -->
    6  <html xmlns="http://www.w3.org/1999/xhtml">
    7     <head><title>Mystery Script</title>
    8        <script type="text/javascript">
    9           <!--
    10           var row = 10;
    11           var column;
    12
    13           while ( row >= 1 )
    14           {
    15              column = 1;
    16
    17              while ( column <= 10 )
    18              {
    19                 document.write( row % 2 == 1 ? "<" : ">" );
    20                 ++column;
    21                } // end while
    22
    23              --row;
    24              document.writeln( "<br />" );
    25           } // end while
    26           // -->
    27        </script>
    28     </head><body></body>
    29  </html>
    

Answer: Answer to 7.20


Section 7.21 Write a JavaScript Program for the following problem.

(Dangling-Else Problem) Determine the output for each of the given segments of code when x is 9 and y is 11, and when x is 11 and y is 9. Note that the interpreter ignores the indentation in a JavaScript program. Also, the JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by the placement of braces ({}). You may not be sure at first glance which if an else matches. This situation is referred to as the “dangling-else” problem. We have eliminated the indentation from the given code to make the problem more challenging. [Hint: Apply the indentation conventions you have learned.]

1. if ( x < 10 )
if ( y > 10 )
document.writeln( "*****<br />" );
else
document.writeln( "#####<br />" );
document.writeln( "$$$$$<br />" );
Answer: when x is 9 and y is 11: *****<br />$$$$$<br />
Answer: when x is 11 and y is 9: $$$$$<br />

2. if ( x < 10 )
{ if ( y > 10 )
document.writeln( "*****<br />" );
}
else
{
document.writeln( "#####<br />" );
document.writeln( "$$$$$<br />" );
}
Answer: when x is 9 and y is 11: *****<br />
Answer: when x is 11 and y is 9: #####<br /> $$$$$<br />


Section 7.22 Write a JavaScript Program for the following problem.

(Another Dangling-Else Problem) Modify the given code to produce the output shown in each part of this problem. Use proper indentation techniques. You may not make any changes other than inserting braces, changing the code indentation and inserting blank lines. The interpreter ignores indentation in JavaScript. We have eliminated the indentation from the given code to make the problem more challenging. [Note: It is possible that no modification is necessary for some of the segments of code.]

        if ( y == 8 )
        if ( x == 5 )
        document.writeln( "@@@@@<br />" );
        else
        document.writeln( "#####<br />" );
        document.writeln( "$$$$$<br />" );
        document.writeln( "&&&&&<br />" );
    

1. Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
$$$$$
&&&&&
Answer:

                if ( y == 8 ){
                    if ( x == 5 ){
                        document.writeln( "@@@@@<br />" );
                    else
                        document.writeln( "#####<br />" );
                    }
                    document.writeln( "$$$$$<br />" );
                    document.writeln( "&&&&&<br />" );
                }
            

Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
Answer:

                if ( y == 8 ){
                    if ( x == 5 ){
                        document.writeln( "@@@@@<br />" );
                    }
                else
                    document.writeln( "#####<br />" );
                    document.writeln( "$$$$$<br />" );
                    document.writeln( "&&&&&<br />" );
                }
            

3. Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
&&&&&
Answer:

                if ( y == 8 ){
                    if ( x == 5 ){
                        document.writeln( "@@@@@<br />" );
                    }
                else
                    document.writeln( "#####<br />" );
                    document.writeln( "$$$$$<br />" );
                }
                document.writeln( "&&&&&<br />" );
                
            

4. Assuming that x = 5 and y = 7, the following output is produced [Note: The last three output statements after the else statements are all part of a block]:
#####
$$$$$
&&&&&
Answer:

                if ( y == 8 ){
                    if ( x == 5 ){
                        document.writeln( "@@@@@<br />" );
                    }
                else
                    document.writeln( "#####<br />" );
                    document.writeln( "$$$$$<br />" );
                    document.writeln( "&&&&&<br />" );
                }
            


Section 7.23 Write a JavaScript Program for the following problem.

Write a script that reads in the size of the side of a square and outputs XHTML text that displays a hollow square of that size constructed of asterisks. Use a prompt dialog to read the size from the user. Your program should work for squares of all side sizes between 1 and 20.
Answer: Answer to 7.23


Section 7.24 Write a JavaScript Program for the following problem.

A palindrome is a number or a text phrase that reads the same backward and forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an alert dialog indicating the problem to the user. Allow the user to enter a new value after dismissing the alert dialog. [Hint: It is possible to do this exercise with the techniques learned in this chapter. You will need to use both division and remainder operations to “pick off” each digit.]
Answer: Answer to 7.24


Section 7.25 Write a JavaScript Program for the following problem.

Write a script that outputs XHTML text that displays the following checkerboard pattern:

            * * * * * * * *
             * * * * * * * *
            * * * * * * * *
             * * * * * * * *
            * * * * * * * *
             * * * * * * * *
            * * * * * * * *
             * * * * * * * *
        

Your program may use only three output statements to display the pattern, one of the form
document.write( "* " );
one of the form
document.write( " " );
and one of the form
document.writeln(); //writes a newline character

You may use XHTML tags (e.g., <pre>) for alignment purposes. [Hint: Repetition structures are required in this exercise.]
Answer: Answer to 7.25


Section 7.26 Write a JavaScript Program for the following problem.

Write a script that outputs XHTML text that keeps displaying in the browser window the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite loop). What happens when you run this program?
Answer: Answer to 7.26


Section 7.27 Write a JavaScript Program for the following problem.

A company wants to transmit data over the telephone, but it is concerned that its phones may be tapped. All of its data is transmitted as four-digit integers. It has asked you to write a program that will encrypt its data so that the data may be transmitted more securely. Your script should read a four-digit integer entered by the user in a prompt dialog and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then output XHTML text that displays the encrypted integer.
Answer: Answer to 7.27


Section 7.28 Write a JavaScript Program for the following problem.

Write a program that inputs an encrypted four-digit integer (from Exercise 7.27) and decrypts it to form the original number.
Answer: Answer to 7.28