Chapter 10 Assignments


Home

Section 10.1 Fill in the blanks in each of the following statement

1. Lists and tables of values can be stored in __________.
Answer: arrays

2. The elements of an array are related by the fact that they normally have the same __________.
Answer: type

3. The number used to refer to a particular element of an array is called its __________.
Answer: subscript

4. The process of putting the elements of an array in order is called __________ the array.
Answer: sorting

5. Determining whether an array contains a certain key value is called __________ the array.
Answer: searching

6. An array that uses two subscripts is referred to as a(n) __________ array.
Answer: two-dimensional


Section 10.2 State whether each of the following is true or false. If false, explain why

1. An array can store many different types of values.
Answer: True

2. An array subscript should normally be a floating-point value.
Answer: False. An array subscript must be an integer or an integer expression

3. An individual array element that is passed to a function and modified in it will contain the modified value when the called function completes execution.
Answer: False. Individual primitive-data-type elements are passed by value. If a reference to an array is passed, then modifications to the elements of the array are reflected in the original element of the array. Also, an individual element of an object type passed to a function is passed by reference, and changes to the object will be reflected in the original array element.


Section 10.3 Write JavaScript statements (regarding array table) to accomplish each of the following tasks.

1. Declare and create the array with three rows and three columns.
Answer: var fractions = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];

2. Display the number of elements.
Answer: fractions[ 3 ]

3. Refer to array element 4.
Answer: fractions[ 4 ]

4. Assign the value 1.667 to array element 9.
Answer: fractions[ 9 ] = 1.667;

5. Assign the value 3.333 to the seventh element of the array.
Answer: fractions[ 6 ] = 3.333;


Section 10.4 Write JavaScript statements (regarding array table) to accomplish each of the following tasks.

1. Declare and create the array with three rows and three columns.
Answer: 1. var table = new Array( new Array( 3 ), new Array( 3 ),new Array( 3 ) );

2. Display the number of elements.
Answer: document.write( "total: " + ( table.length * table[ 0 ].length ) );

3. Use a for...in statement to initialize each element of the array to the sum of its subscripts. Assume that the variables x and y are declared as control variables.
Answer:

for ( var x in table )
                for ( var y in table[ x ] )
                    table[ x ][ y ] = x + y;
        


Section 10.5 Find the error(s) in each of the following program segments, and correct them.

1.

            var b = new Array( 10 );
            for ( var i = 0; i <= b.length; ++i )
               b[ i ] = 1;  
        
Answer: Error: Referencing an array element outside the bounds of the array (b[10]). [Note: This error is actually a logic error, not a syntax error.] Correction: Change the <= operator to <.

2.

            var a = [ [ 1, 2 ], [ 3, 4 ] ];
                a[ 1, 1 ] = 5;
  
        
Answer: Error: The array subscripting is done incorrectly. Correction: Change the statement to a[ 1 ][ 1 ] = 5;.


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

1. JavaScript stores lists of values in __________.
Answer: Arrays

2. The names of the four elements of array p are __________, __________, __________ and __________.
Answer: p[0], p[1],p[2],p[3]

3. In a two-dimensional array, the first subscript identifies the __________ of an element, and the second subscript identifies the __________ of an element.
Answer: rows, columns

4. An m-by-n array contains __________ rows, __________ columns and __________ elements.
Answer: m, n, m*n

5. The name the element in row 3 and column 5 of array d is __________.
Answer: d[2,4]

6. The name of the element in the third row and fifth column of array d is __________.
Answer: d[2,4]


Section 10.7 State whether each of the following is true or false. If false, explain why

1. To refer to a particular location or element in an array, we specify the name of the array and the value of the element.
Answer: False, use the name of the array and the index.

2. A variable declaration reserves space for an array.
Answer: false

3. To indicate that 100 locations should be reserved for integer array p, the programmer should write the declaration p[ 100 ];
Answer: false, var p = aew Array(100); should be used

4. A JavaScript program that initializes the elements of a 15-element array to zero must contain at least one for statement.
Answer: false, you can initialize an array in muliptle ways, with or without a for loop.

5. A JavaScript program that totals the elements of a two-dimensional array must contain nested for statements.
Answer: false, this is just one option of programming it.


Section 10.8 Write JavaScript statements to accomplish each of the following tasks.

1. Display the value of the seventh element of array f.
Answer: Lots of ways to disply, but to reference the element use f[6];

2. Initialize each of the five elements of one-dimensional array g to 8.
Answer: var g[8,8,8,8,8]

3. Total the elements of array c, which contains 100 numeric elements.
Answer:

for(ii=0; ii<100; ii++)
                    total+=c[ii];

4. Copy 11-element array a into the first portion of array b, which contains 34 elements.
Answer: for(ii=0; ii<11; ii++) b[ii] = a[ii];

5. Determine and print the smallest and largest values contained in 99-element floating-point array w.
Answer:

var sorted = a.sort(function(a, b){return a-b});
        document.writeline("smallest: " + sorted[0]);
        document.writeline("largest: " + sorted[98]);


Section 10.9 Consider a two-by-three array t that will store integers.

1. Write a statement that declares and creates array t.
Answer: Not Required

2. How many rows does t have?
Answer: Not Required

3. How many columns does t have?
Answer: Not Required

4. How many elements does t have?
Answer: Not Required

5. Write the names of all the elements in the second row of t.
Answer: Not Required

6. Write the names of all the elements in the third column of t.
Answer: Not Required

7. Write a single statement that sets the elements of t in row 1 and column 2 to zero.
Answer: Not Required

8. Write a series of statements that initializes each element of t to zero. Do not use a repetition structure.
Answer: Not Required

9. Write a nested for statement that initializes each element of t to zero.
Answer: Not Required

10. Write a series of statements that determines and prints the smallest value in array t.
Answer: Not Required

11. Write a statement that displays the elements of the first row of t.
Answer: Not Required

12. Write a statement that totals the elements of the fourth column of t.
Answer: Not Required

13. Write a series of statements that prints the array t in neat, tabular format. List the column subscripts as headings across the top, and list the row subscripts at the left of each row.
Answer: Not Required


Section 10.10 Write a javascript script for the following.

Use a one-dimensional array to solve the following problem: A 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 grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a total of $650. Write a script (using an array of counters) that obtains the gross sales for each employee through an XHTML form and determines how many of the salespeople earned salaries in each of the following ranges (assume that each salesperson’s salary is truncated to an integer amount):
1. $200–299
2. $300–399
3. $400–499
4. $500–599
5. $600–699
6. $700–799
7. $800–899
8. $900–999
9. $1000 and over
Answer: answer to 10.10


Section 10.11 Write statements that perform the following operations for a one-dimensional array.

1. Set the 10 elements of array counts to zeros.
Answer:

            for(ii=0;ii<10;ii++){
                counts[ii] = 0;
            }
            

2. Add 1 to each of the 15 elements of array bonus.
Answer:

            for(ii=0;ii<15;ii++){
                bonus[ii]+=1;
            }
            

3. Display the five values of array bestScores, separated by spaces.
Answer:

            for(ii=0;ii<5;ii++){
               document.write(bestScores[ii] + " ");
            }
            


Section 10.12 Write a javascript script for the following.

Use a one-dimensional array to solve the following problem: Read in 20 numbers, each of which is between 10 and 100. As each number is read, print it only if it is not a duplicate of a number that has already been read. Provide for the “worst case,” in which all 20 numbers are different. Use the smallest possible array to solve this problem.
Answer: answer to 10.12


Section 10.13

Label the elements of three-by-five two-dimensional array sales to indicate the order in which they are set to zero by the following program segment:

            for ( var row in sales )
                for ( var col in sales[ row ] )
                    sales[ row ][ col ] = 0;
        
Answer: 0,0;0,1;0,2;0,3;0,4;1,0;1,1;1,2;1,3;1,4;2,0;2,1;2,2;2,3


Section 10.14 Write a javascript script for the following

Write a script to simulate the rolling of two dice. The script should use Math.random to roll the first die and again to roll the second die. The sum of the two values should then be calculated. [Note: Since each die can show an integer value from 1 to 6, the sum of the values will vary from 2 to 12, with 7 being the most frequent sum, and 2 and 12 the least frequent sums. Figure 10.15 shows the 36 possible combinations of the two dice. Your program should roll the dice 36,000 times. Use a one-dimensional array to tally the numbers of times each possible sum appears. Display the results in an XHTML table. Also determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately 1/6 of all the rolls should be 7).]
table
Answer: Not Required


Section 10.15 Write a javascript script for the following

Write a script that runs 1000 games of craps and answers the following questions:
1. How many games are won on the first roll, second roll, ..., twentieth roll and after the twentieth roll?
2. How many games are lost on the first roll, second roll, ..., twentieth roll and after the twentieth roll?
3. What are the chances of winning at craps? [Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?]
4. What is the average length of a game of craps?
5. Do the chances of winning improve with the length of the game?
Answer: Not Required


Section 10.16 Write a javascript script for the following

(Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. You have been asked to program the new system. You are to write a program to assign seats on each flight of the airline’s only plane (capacity: 10 seats). Your program should display the following menu of alternatives: Please type 1 for "First Class" and Please type 2 for "Economy". If the person types 1, your program should assign a seat in the first-class section (seats 1–5). If the person types 2, your program should assign a seat in the economy section (seats 6–10). Your program should print a boarding pass indicating the person’s seat number and whether it is in the first-class or economy section of the plane. Use a one-dimensional array to represent the seating chart of the plane. Initialize all the elements of the array to 0 to indicate that all the seats are empty. As each seat is assigned, set the corresponding elements of the array to 1 to indicate that the seat is no longer available. Your program should, of course, never assign a seat that has already been assigned. When the first-class section is full, your program should ask the person if it is acceptable to be placed in the economy section (and vice versa). If yes, then make the appropriate seat assignment. If no, then print the message "Next flight leaves in 3 hours."
Answer: Not Required


Section 10.17 Write a javascript script for the following

Use a two-dimensional array to solve the following problem: A company has four salespeople (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each different type of product actually sold. Each slip contains
1. the salesperson number,
2. the product number, and
3. the total dollar value of the product sold that day.
Thus, each salesperson passes in between zero and five sales slips per day. Assume that the information from all of the slips for last month is available. Write a script that will read all this information for last month’s sales and summarize the total sales by salesperson by product. All totals should be stored in the two-dimensional array sales. After processing all the information for last month, display the results in an XHTML table format, with each of the columns representing a different salesperson and each of the rows representing a different product. Cross-total each row to get the total sales of each product for last month; cross-total each column to get the total sales by salesperson for last month. Your tabular printout should include these cross-totals to the right of the totaled rows and to the bottom of the totaled columns.
Answer: Not Required


Section 10.18 Write a javascript script for the following

(Turtle Graphics) The Logo language, which is popular among young computer users, made the concept of turtle graphics famous. Imagine a mechanical turtle that walks around the room under the control of a JavaScript program. The turtle holds a pen in one of two positions, up or down. When the pen is down, the turtle traces out shapes as it moves; when the pen is up, the turtle moves about freely without writing anything. In this problem, you will simulate the operation of the turtle and create a computerized sketchpad as well. Use a 20-by-20 array floor that is initialized to zeros. Read commands from an array that contains them. Keep track of the current position of the turtle at all times and of whether the pen is currently up or down. Assume that the turtle always starts at position (0, 0) of the floor, with its pen up. The set of turtle commands your script must process are as in Fig. 10.16.
1 Pen up
2 Pen down
3 Turn right
4 Turn left
5,10 Move forward 10 spaces (or a number other than 10)
6 Print the 20-by-20 array
9 End of data (sentinel)
Suppose that the turtle is somewhere near the center of the floor. The following “program” would draw and print a 12-by-12 square, then leave the pen in the up position:
2
5,12
3
5,12
3
5,12
3
5,12
1
6
9
As the turtle moves with the pen down, set the appropriate elements of array floor to 1s. When the 6 command (print) is given, display an asterisk or some other character of your choosing wherever there is a 1 in the array. Wherever there is a zero, display a blank. Write a script to implement the turtle-graphics capabilities discussed here. Write several turtle-graphics programs to draw interesting shapes. Add other commands to increase the power of your turtle-graphics language.
Answer: Not Required


Section 10.19 Write a javascript script for the following

(The Sieve of Eratosthenes) A prime integer is an integer greater than 1 that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is an algorithm for finding prime numbers. It operates as follows:
1. Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will remain as 1. All other array elements will eventually be set to zero.
2. Set the first two elements to zero, since 0 and 1 are not prime. Starting with array subscript 2, every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all elements beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for array subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.); and so on. When this process is complete, the array elements that are still set to 1 indicate that the subscript is a prime number. These subscripts can then be printed. Write a script that uses an array of 1000 elements to determine and print the prime numbers between 1 and 999. Ignore element 0 of the array.
Answer: Not Required


Section 10.20Write a javascript script for the following

(Simulation: The Tortoise and the Hare) In this problem, you will re-create one of the truly great moments in history, namely the classic race of the tortoise and the hare. You will use random number generation to develop a simulation of this memorable event. Our contenders begin the race at square 1 of 70 squares. Each square represents a possible position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground. There is a clock that ticks once per second. With each tick of the clock, your script should adjust the position of the animals according to the rules in Fig. 10.17.

Table 10.17. Rules for adjusting the position of the tortoise and the hare.
Animal Move type Percentage of the time Actual move
Tortoise Fast plod 50% 3 squares to the right
Slip 20% 6 squares to the left
Slow plod 30% 1 square to the right
Hare Sleep 20% No move at all
Big hop 20% 9 squares to the right
Big slip 10% 12 squares to the left
Small hop 30% 1 square to the right
Small slip 20% 2 squares to the left

Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70). Start each animal at position 1 (i.e., the “starting gate”). If an animal slips left before square 1, move the animal back to square 1. Generate the percentages in Fig. 10.17 by producing a random integer i in the range 1 ≤ i ≤ 10. For the tortoise, perform a “fast plod” when 1 ≤ i ≤ 5, a “slip” when 6 ≤ i ≤ 7 and a “slow plod” when 8 ≤ i ≤ 10. Use a similar technique to move the hare. Begin the race by printing
BANG !!!!!
AND THEY'RE OFF !!!!!
Then, for each tick of the clock (i.e., each repetition of a loop), print a 70-position line showing the letter T in the position of the tortoise and the letter H in the position of the hare. Occasionally, the contenders will land on the same square. In this case, the tortoise bites the hare, and your script should print OUCH!!! beginning at that position. All print positions other than the T, the H or the OUCH!!! (in case of a tie) should be blank. After each line is printed, test whether either animal has reached or passed square 70. If so, print the winner, and terminate the simulation. If the tortoise wins, print TORTOISE WINS!!! YAY!!! If the hare wins, print Hare wins. Yuck! If both animals win on the same tick of the clock, you may want to favor the turtle (the “underdog”), or you may want to print It's a tie. If neither animal wins, perform the loop again to simulate the next tick of the clock. When you are ready to run your script, assemble a group of fans to watch the race. You’ll be amazed at how involved your audience gets!
Later in the book, we introduce a number of Dynamic HTML capabilities, such as graphics, images, animation and sound. As you study those features, you might enjoy enhancing your tortoise-and-hare contest simulation.
Answer: Not Required