Chapter 9 Assignments


Home

Section 9.1 Fill in the blanks in each of the following statements:

1. Program modules in JavaScript are called ________ .
Answer: functions

2. A function is invoked using a(n) ________.
Answer: function call

3. A variable known only inside the function in which it is defined is called a(n) ________.
Answer: local variable

4. The ________ statement in a called function can be used to pass the value of an expression back to the calling function.
Answer: return

5. The keyword ________ indicates the beginning of a function definition.
Answer: function


Section 9.2 Answer the following

For the given program, state the scope (either global scope or function scope) of each of the following elements:

        1  <?xml version="1.0" encoding="utf-8" ?>
        2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        4
        5  <!-- Exercise 9.2: cube.html -->
        6  <html xmlns="http://www.w3.org/1999/xhtml">
        7     <head>
        8        <title>Scoping</title>
        9        <script type="text/javascript">
        10           <!--
        11           var x;
        12  
        13           function output()
        14           {
        15              for ( x = 1; x <= 10; x++ )
        16                 document.writeln( cube( x ) + "<br />" );
        17           } // end function output
        18
        19           function cube( y )
        20           {
        21              return y * y * y;
        22           } // end function cube
        23           // -->
        24     </script>
        25     </head><body onload="output()"></body>
        26  </html>
    

1. The variable x.
Answer: Global scope

2. The variable y.
Answer: Function scope

3. The function cube.
Answer: Global scope

4. The function output.
Answer: Global scope


Section 9.3 Fill in the blanks in each of the following statements:

1. Programmer-defined functions, global variables and JavaScript’s global functions are all part of the ________ object.
Answer: Global

2. Function ________ determines if its argument is or is not a number.
Answer: isNaN

3. Function ________ takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set are encoded in a hexadecimal format.
Answer: escape

4. Function ________ takes a string argument representing JavaScript code to execute.
Answer: eval

5. Function ________ takes a string as its argument and returns a string in which all characters that were previously encoded with escape are decoded.
Answer: unescape


Section 9.4 Fill in the blanks in each of the following statements:

1. An identifier’s ________ is the portion of the program in which the it can be used.
Answer: scope

2. The three ways to return control from a called function to a caller are ________, and ________.
Answer: return; or return expression; or encountering the closing right brace of a function

3. The ________ function is used to produce random numbers.
Answer: Math.random

4. Variables declared in a block or in a function’s parameter list are of ________ scope.
Answer: local


Section 9.5 Locate the error in each of the following program segments and explain how to correct it:

1.

 method g()
        {
        document.writeln( "Inside method g" );
        }
        

Answer: Error: method is not the keyword used to begin a function definition. Correction: Change method to function.

2.

 // This function should return the sum of its arguments
        function sum( x, y )
        {
        var result;
        result = x + y;
        }

Answer: Error: The function is supposed to return a value, but does not. Correction: Either delete variable result and place the statement return x + y; in the function or add the following statement at the end of the function body: return result;

3.

function f( a );
        {
        document.writeln( a );
        }

Answer: Error: The semicolon after the right parenthesis that encloses the parameter list. Correction: Delete the semicolon after the right parenthesis of the parameter list


Section 9.6 Write a program for the following.

Write a complete JavaScript program to prompt the user for the radius of a sphere, and call function sphereVolume to calculate and display the volume of the sphere. Use the statement volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ); to calculate the volume. The user should input the radius through an XHTML text field in a <form> and click an XHTML button to initiate the calculation.
Answer: answer to 9.06


Section 9.7 Write a script for the following

Write a script that prompts the user for the radius of a circle, uses a function circleArea to calculate the area of the circle, and prints the area of the circle.
Answer: Answer to 9.07


Section 9.8 Write a script for the following

A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a script that calculates and displays the parking charges for each customer who parked a car in this garage yesterday. You should input from the user the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday’s receipts. The program should use the function calculateCharges to determine the charge for each customer. Use a text input field to obtain the input from the user.
Answer: Not Required


Section 9.9 Write a function for the following

Write function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be floating-point values. Incorporate this function into a script that enables the user to enter the coordinates of the points through an XHTML form.
Answer: answer to 9.9


Section 9.10 Answer each of the following questions:

1. What does it mean to choose numbers “at random”?
Answer: The computer gives a random number.

2. Why is the Math.random function useful for simulating games of chance?
Answer: it allows answers to not be known ahead of time.

3. Why is it often necessary to scale and/or shift the values produced by Math.random?
Answer: often random numbers must be in a certain range.

4. Why is computerized simulation of real-world situations a useful technique?
Answer: Allows end users to try different real world issues and determine possible outcomes


Section 9.11 Write statements that assign random integers to the variable n in the following ranges:

1. 1 ≤ n ≤ 2
Answer: Not Required

2. 1 ≤ n ≤ 100
Answer: Not Required

3. 0 ≤ n ≤ 9
Answer: Not Required

4. 1000 ≤ n ≤ 1112
Answer: Not Required

5. –1 ≤ n ≤ 1
Answer: Not Required

6. –3 ≤ n ≤ 11
Answer: Not Required


Section 9.12 For each of the following sets of integers, write a single statement that will print a number at random from the set:

1. 2, 4, 6, 8, 10.
Answer: Not Required

2. 3, 5, 7, 9, 11.
Answer: Not Required

3. 6, 10, 14, 18, 22.
Answer: Not Required


Section 9.13 Write a function for the following

Write a function integerPower( base, exponent ) that returns the value ofbase exponent
For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent and base are integers. Function integerPower should use a for or while statement to control the calculation. Incorporate this function into a script that reads integer values from an XHTML form for base and exponent and performs the calculation with the integerPower function. The XHTML form should consist of two text fields and a button to initiate the calculation. The user should interact with the program by typing numbers in both text fields then clicking the button.
Answer: answer to 9.13


Section 9.14 Write a function for the following

Write a function multiple that determines, for a pair of integers, whether the second integer is a multiple of the first. The function should take two integer arguments and return true if the second is a multiple of the first, and false otherwise. Incorporate this function into a script that inputs a series of pairs of integers (one pair at a time). The XHTML form should consist of two text fields and a button to initiate the calculation. The user should interact with the program by typing numbers in both text fields, then clicking the button
Answer: Not Required


Section 9.15 Write a script for the following

Write a script that inputs integers (one at a time) and passes them one at a time to function isEven, which uses the modulus operator to determine whether an integer is even. The function should take an integer argument and return true if the integer is even and false otherwise. Use sentinel-controlled looping and a prompt dialog.
Answer: Not Required


Section 9.16 Write a function for the following

Write a function squareOfAsterisks that displays a solid square of asterisks whose side is specified in integer parameter side. For example, if side is 4, the function displays
Incorporate this function into a script that reads an integer value for side from the user at the keyboard and performs the drawing with the squareOfAsterisks function.
****
****
****
****
Answer: Not Required


Section 9.17 Write a function for the following

Modify the script created in Exercise 9.16 to also prompt the user for a character which will be used to create the square. Thus, if side is 5 and fillCharacter is #, the function should print
####
####
####
####
Answer: Not Required


Section 9.18 Write program segments that accomplish each of the following tasks:

1. Calculate the integer part of the quotient when integer a is divided by integer b.
Answer: Not Required

2. Calculate the integer remainder when integer a is divided by integer b.
Answer: Not Required

3. Use the program pieces developed in parts (a) and (b) to write a function displayDigits that receives an integer between 1 and 99999 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should be printed as 4 5 6 2
Answer: Not Required

4. Incorporate the function developed in part (c) into a script that inputs an integer from a prompt dialog and invokes displayDigits by passing to the function the integer entered.
Answer: Not Required


Section 9.19 Implement the following functions:

1. Function celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation C = 5.0 / 9.0 * ( F - 32 );
Answer: Not Required

2. Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation F = 9.0 / 5.0 * C + 32;
Answer: Not Required

3. Use these functions to write a script that enables the user to enter either a Fahrenheit or a Celsius temperature and displays the Celsius or Fahrenheit equivalent. Your XHTML document should contain two buttons—one to initiate the conversion from Fahrenheit to Celsius and one to initiate the conversion from Celsius to Fahrenheit.
Answer:


Section 9.20 Write a function for the following

Write a function minimum3 that returns the smallest of three floating-point numbers. Use the Math.min function to implement minimum3. Incorporate the function into a script that reads three values from the user and determines the smallest value.
Answer: Not Required


Section 9.21 Write a function for the following

An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a script that determines and displays all the perfect numbers between 1 and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results in a <textarea>.
Answer: answer to 9.21


Section 9.22 Write a function for the following

An integer is said to be prime if it is greater than 1 and divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
1. Write a function that determines whether a number is prime.
2. Use this function in a script that determines and prints all the prime numbers between 1 and 10,000. How many of these 10,000 numbers do you really have to test before being sure that you have found all the primes? Display the results in a <textarea>
3. Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you only need go as high as the square root of n. Why? Rewrite the program using the Math.sqrt method to calculate the square root, and run it both ways. Estimate the performance improvement.
Answer: answer to 9.22


Section 9.23 Write a function for the following

Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the function should return 1367. Incorporate the function into a script that reads a value from the user. Display the result of the function in the status bar.
Answer: Not Required


Section 9.24 Write a function for the following

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write a function gcd that returns the greatest common divisor of two integers. Incorporate the function into a script that reads two values from the user.
Answer: Not Required


Section 9.25 Write a function for the following

Write a function qualityPoints that inputs a student’s average and returns 4 if the student’s average is 90–100, 3 if the average is 80–89, 2 if the average is 70–79, 1 if the average is 60–69 and 0 if the average is lower than 60. Incorporate the function into a script that reads a value from the user.
Answer: Not Required


Section 9.26 Write a function for the following

Write a script that simulates coin tossing. Let the program toss the coin each time the user clicks the Toss button. Count the number of times each side of the coin appears. Display the results. The program should call a separate function flip that takes no arguments and returns false for tails and true for heads. [Note: If the program realistically simulates the coin tossing, each side of the coin should appear approximately half the time.]
Answer: answer to 9.26


Section 9.27 Write a function for the following

Computers are playing an increasing role in education. Write a program that will help an elementary-school student learn multiplication. Use Math.random to produce two positive one-digit integers. It should then display a question such as
How much is 6 times 7?
The student then types the answer into a text field. Your program checks the student’s answer. If it is correct, display the string "Very good!" and generate a new question. If the answer is wrong, display the string "No. Please try again." and let the student try the same question again repeatedly until the student finally gets it right. A separate function should be used to generate each new question. This function should be called once when the script begins execution and each time the user answers the question correctly.
Answer: Not Required


Section 9.28 Write a function for the following

The use of computers in education is referred to as computer-assisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This problem can be eliminated by varying the computer’s dialogue to hold the student’s attention. Modify the program in Exercise 9.27 to print one of a variety of comments for each correct answer and each incorrect answer. The set of responses for correct answers is as follows:
Very good!
Excellent!
Nice work!
Keep up the good work!
The set of responses for incorrect answers is as follows:
No. Please try again.
Wrong. Try once more.
Don't give up!
No. Keep trying.
Use random number generation to choose a number from 1 to 4 that will be used to select an appropriate response to each answer. Use a switch statement to issue the responses.

Answer: answer to 9.28


Section 9.29 Write a function for the following

More sophisticated computer-assisted instruction systems monitor the student’s performance over a period of time. The decision to begin a new topic is often based on the student’s success with previous topics. Modify the program in Exercise 9.28 to count the number of correct and incorrect responses typed by the student. After the student answers 10 questions, your program should calculate the percentage of correct responses. If the percentage is lower than 75 percent, print Please ask your instructor for extra help, and reset the program so another student can try it.
Answer:


Section 9.30 Write a function for the following

Write a script that plays a “guess the number” game as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The script displays the prompt Guess a number between 1 and 1000 next to a text field. The player types a first guess into the text field and clicks a button to submit the guess to the script. If the player’s guess is incorrect, your program should display Too high. Try again. or Too low. Try again. to help the player “zero in” on the correct answer and should clear the text field so the user can enter the next guess. When the user enters the correct answer, display Congratulations. You guessed the number! and clear the text field so the user can play again. [Note: The guessing technique employed in this problem is similar to a binary search, which we discuss in Chapter 10, JavaScript: Arrays.]
Answer:


Section 9.31 Write a function for the following

Modify the program of Exercise 9.30 to count the number of guesses the player makes. If the number is 10 or fewer, display Either you know the secret or you got lucky! If the player guesses the number in 10 tries, display Ahah! You know the secret! If the player makes more than 10 guesses, display You should be able to do better! Why should it take no more than 10 guesses? Well, with each good guess, the player should be able to eliminate half of the numbers. Now show why any number 1 to 1000 can be guessed in 10 or fewer tries.
Answer:


Section 9.32 Write a function for the following

Exercises 9.27 through 9.29 developed a computer-assisted instruction program to teach an elementary-school student multiplication. This exercise suggests enhancements to that program.
1. Modify the program to allow the user to enter a grade-level capability. A grade level of 1 means to use only single-digit numbers in the problems, a grade level of 2 means to use numbers as large as two digits, and so on.
2. Modify the program to allow the user to pick the type of arithmetic problems he or she wishes to study. An option of 1 means addition problems only, 2 means subtraction problems only, 3 means multiplication problems only, 4 means division problems only and 5 means to intermix randomly problems of all these types.
Answer:


Section 9.33 Write a function for the following

Modify the craps program in Fig. 9.6 to allow wagering. Initialize variable bankBalance to 1000 dollars. Prompt the player to enter a wager. Check that the wager is less than or equal to bankBalance and, if not, have the user reenter wager until a valid wager is entered. After a valid wager is entered, run one game of craps. If the player wins, increase bankBalance by wager, and print the new bankBalance. If the player loses, decrease bankBalance by wager, print the new bankBalance, check whether bankBalance has become zero and, if so, print the message Sorry. You busted! As the game progresses, print various messages to create some chatter, such as Oh, you're going for broke, huh? or Aw c'mon, take a chance! or You're up big. Now's the time to cash in your chips!. Implement the chatter as a separate function that randomly chooses the string to display.
Answer: answer to 9.33


Section 9.34 Write a function for the following

Write a recursive function power( base, exponent ) that, when invoked, returns
baseexponent
for example, power( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. The recursion step would use the relationship
baseexponent= base · baseexponent –1
and the terminating condition occurs when exponent is equal to 1, because
base1= base
Incorporate this function into a script that enables the user to enter the base and exponent.
Answer:


Section 9.35 Write a function for the following

(Visualizing Recursion) It is interesting to watch recursion in action. Modify the factorial function in Fig. 9.11 to display its local variable and recursive-call parameter. For each recursive call, display the outputs on a separate line and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text.
Answer:


Section 9.36 What does the following function do?

             // Parameter b must be a positive
            // integer to prevent infinite recursion
            function mystery( a, b )
            {
               if ( b == 1 )
                  return a;
               else
                  return a + mystery( a, b - 1 );
            }
        
Answer: answer to 9.36