9.1 Fill in the blanks in each of the following statements:
- Program modules in JavaScript are called functions.
- A function is invoked using a(n) function call.
- A variable known only inside the function in which it is defined is called a(n) local variable.
- The return statement in a called function can be used to pass the value of an expression back to the calling function.
- The keyword function indicates the begining of a function definition.
9.2 For the given program, state the scope (either global scope or function scope) of each of the following elements:
- The variable x. Global scope.
- The variable y. Function scope.
- The function cube. Global scope.
- The function output. Global scope.
9.3 Fill in the blanks in each of the following statements:
- Programmer-defined functions, global variables and JavaScript's global functions are all part of the Global object.
- Function isNaN determines if its argument is or is not a number.
- Function escape 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.
- Function eval takes a string argument representing JavaScript code to execute.
- Function unescape takes a string as its argument and returns a string in which all characters that were previously encoded with escape are decoded.
9.4 Fill in the blanks in each of the following statements:
- An identifier's scope is the portion of the program in which it can be used.
- The three ways to return control from a called function to a caller are return, return expression and encountering the closing right brace of a function.
- The Math.random function is used to produce random numbers.
- Variables declared in a block or in a function's parameter list are of local scope.
9.5 Locate the error in each of the following program segments and explain how to correct it:
Error: Method is not the keyword used to begin a function definition. Correction: Change method to function.
function g()
{
document.writeln( "Inside method g" );
}
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;.
function sum( x, y )
{
var result;
result = x + y;
return result;
}
Error: The semicolon after the right parenthesis that encloses the parameter list. Correction: Delete the semicolon after the right parenthesis of the parameter list.
function f( a )
{
document.writeln( a );
}
9.6 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.
9.7 Write a script that prompts the user for the radius of a circle, uses a function circleArea to calculate the area of a circle, and prints the area of the circle.
9.9 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.
9.10 Answer each of the following questions:
- What does it mean to choose numbers "at random"?
Choosing a number at random means to select a specific number from a range of numbers where each number has an equal chance of being selected. - Why is the Math.random function useful for simulating games of chance?
Math.random can be useful to simulate the rolling of dice, drawing of cards, or selecting any object from a group with an equal chance of selection. - Why is it often necessary to scale and/or shift the values produced by Math.random?
It is necessary to scale or shift the values produced by Math.random when the program requires values outside the range from 0 up to, but not including, 1. - Why is computerized simulation of real-world situations a useful technique?
Computer simulations allow us to analyze hypothetical situations and create predictions of real-world events.
9.21 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>.
9.22 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.
- Write a function that determines whether a number is prime.
function prime( number )
{
for ( var test = 2; test <= number / 2; test++ )
{
if ( number % test == 0 )
return false;
} // end for
return true;
} // end function prime
- 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>.
9.22b Answer - 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.
function prime( number )
{
for ( var test = 2; test <= Math.sqrt( number ); test++ )
{
if ( number % test == 0 )
return false;
} // end for
return true;
} // end function prime
9.22c Answer
9.26 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.]
9.27 Computers are playing an increasing role in educaton. 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.
(for reference only, used in question 9.28)
9.28 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 chose 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.
9.33 Modify the craps program in Fig. 9.6 to allow wagering. Inititalize 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 the 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 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.
9.36 What does the following function do?
This function adds a to itself for b number of times. For example, mystery( 5, 3 ) results in 15, ( 5 + 5 + 5 ).