Additional Practice Exercises (with Solutions)

Ch2 | Ch4 | Ch5 | Ch7 | Ch9 | Ch11 | Ch13 | Ch15 | Ch17

Chapter 2

The next four exercises refer to the following HTML document:

<!doctype html> <!-- test1.html Sample page for Test 1 --> <!-- ======================================= --> <html> <head> <title>Omaha Page</title> </head> <body> <div style="text-align:center"> <img src="omaha.jpg" alt="Photo of Omaha Skyline"> <h1>Omaha, Nebraska</h1> </div> <p>Omaha is the largest city in the state of <a href="http://www.nebraska.gov">Nebraska</a>, and is the county seat of Douglas County. <br> According to the 2010 Census, Omaha is the 42nd largest city in the United States. <i>Omaha</i> is a native-American word that means <i>dwellers on the bluff</i>. </p> <h3>Facts about Omaha</h3> <table style="border-style:solid"> <tr><td>Founded: </td> <td>1854 </td></tr> <tr><td>Incorporated: </td> <td>1857 </td></tr> <tr><td>Population: </td> <td> 408,958 (city limits)</td></tr> <tr><td></td><td> 865,350 (metropolitan)</td></tr> </table> <h3>Fortune 500 headquarters in Omaha:</h3> <ul> <li> ConAgra Foods </li> <li> Union Pacific Corporation </li> <li> Mutual of Omaha </li> <li> Peter Kiewit and Sons, Inc. </li> <li> Berkshire Hathaway </li> </ul> <hr> <p style="text-align:right">source: <a href="http://en.wikipedia.org/wiki/Omaha,_Nebraska"> Wikipedia</a></p> </body> </html>

Exercise 2A

Draw a picture of the Web page that would be generated by the above HTML document. Be specific with respect to formatting and page layout.

view solution

Exercise 2B

What is the purpose of the tags that begin <!-- and end -->? Would omitting the two lines that contain these tags cause the page to be displayed any differently?

view solution

Exercise 2C

In what directory must the image file omaha.jpg be stored in order for it to be loaded into the page correctly? What would happen if the image could not be found? That is, what would appear in the page if the image failed to load?

view solution

Exercise 2D

What would happen if the user were to click on the link at the bottom of this page? What if the user's computer were not connected to the Internet?

view solution


Chapter 4

The next four exercises refer to the following HTML document:

<!doctype html> <html> <head> <title>Barnyard Fun</title> </head> <body> <h1>Spin and Speak</h1> <p> <input type="button" value="Cow" onclick="document.getElementById('animalSpan').innerHTML='cow'; document.getElementById('soundSpan').innerHTML='moo';"> <input type="button" value="Horse" onclick="document.getElementById('animalSpan').innerHTML='horse'; document.getElementById('soundSpan').innerHTML='neigh';"> </p> <p>The <span id="animalSpan">???</span> goes <span id="soundSpan">???</span>. </body> </html>

Exercise 4A

Draw a picture of the Web page that would be generated by the above HTML document. Be specific with respect to formatting and page layout.

view solution

Exercise 4B

Describe the changes that would occur within the page when one of the buttons is clicked.

view solution

Exercise 4C

Suppose the developer of the page had made a typing error, misspelling the name animalSpan in one of the button's ONCLICK attribute, e.g., animulSpan. Would this page still load and look the same in the browser? Would it behave the same when that button is clicked?

view solution

Exercise 4D

Modify the page so that there is an image above the buttons. Initially, this image should display the question mark icon used in the book (balance3e.com/Images/mystery.gif). When a button is clicked, in addition to the current behavior, the image should change to display a picture of that animal (either cow.jpg or horse.jpg).

view solution


Chapter 5

The next two exercises refer to the following JavaScript statements, which access a student's grade from a text box and display a scaled grade in a page division.

scaleAmt = Math.floor(Math.random()*5); grade = document.getElementById('gradeBox').value; newGrade = grade + scaleAmt; document.getElementById('outputDiv').innerHTML = 'Your grade is' + newGrade + '.';

Exercise 5A

The first statement determines the amount by which the grade will be scaled. What is the possible range of scale amounts? That is, what are the smallest and largest possible scale amounts? Can the scale amount be a fraction, or will it always be a whole integer?

view solution

Exercise 5B

This code contains a logic error that will result in scaled grades well outside the specified range. For example, it is possible for the user to enter a grade of 90 in the text box, then see the following message when the code is executed: Your grade is 903. What is the cause of this error? How must the code be modified so that the resulting scaled grade is always within the specified range?

view solution

The next four exercises refer to the following HTML document, which could be used by a person to select their favorite animal. You may assume that the following four images are stored in the same folder as this page: dog.jpg, cat.jpg, and horse.jpg, and mystery.gif (a question mark).

<!doctype html> <html> <head> <title>Animal Page</title> </head> <body> <div style="text-align:center"> <img id="animalImg" src="mystery.gif" alt="animal picture"> </div> <p> What is your favorite kind of animal? <input type="text" id="animalBox" size=20 value="e.g., cat"> </p> <input type="button" value="Submit your pick" onclick="animal = document.getElementById('animalBox').value; document.getElementById('outputDiv').innerHTML = 'I like ' + animal + 's too!';"> <hr> <div id="outputDiv"> <i>You can judge a man's true character by the way he treats his fellow animals.</i> <br> -- Paul McCartney</div> </div> </body> </html>

Exercise 5C

Draw a picture of the Web page that would be displayed when this HTML document is loaded. Your drawing should clearly show the layout of the page elements, along with any text, labels, and default values, as they would initially appear in the page.

view solution

Exercise 5D

Suppose the user entered a type of animal in the text box then clicked on the button. What would happen in the page? Be specific.

view solution

Exercise 5E

Augment the above page so that, in addition to its current behavior, the image in the page is updated to display the chosen animal. For example, if the user entered cat in the text box, then the page should display the image stored in cat.jpg.

view solution

Exercise 5F

What would happen in your modified page if the user entered an animal for which there was no corresponding image? For example, if the user entered llama in the box, but there was no llama.jpg image file?

view solution


Chapter 7

The next three exercises refer to the following HTML document, which could be used by a person to calculate the hypotenuse of a right triangle. Given the lengths of the two sides a and b of a right triangle, the length of the third side c (the hypotenuse) is: .

<!doctype html> <html> <head> <title>Right Triangle Calculator</title> <script type="text/javascript"> function Triangulate() // Assumes: aBox and bBox contain the lengths of the two sides of a right triangle // Results: computes and displays the 3rd side (the hypotenuse) & perimeter in outputDiv { // CODE TO BE COMPLETED IN EXERCISE 7C } </script> </head> <body> <h2 style="text-align:center">Right Triangle Calculator <br> Find the Hypotenuse & Perimeter</h2> <p> <table> <tr><td>Lengths of the two sides: </td> <td><input type="text" id="aBox" size=8 value=30> </td></tr> <tr><td> </td> <td><input type="text" id="bBox" size=8 value=40> </td></tr> </table> </p> <input type="button" value="Analyze the Triangle" onclick="Triangulate();"> <hr><div id="outputDiv"></div> </body> </html>

Exercise 7A

Draw a picture of the Web page that would be displayed when this HTML document is loaded. Your drawing should clearly show the layout of the page elements, along with any text, labels, and default values, as they would initially appear in the page.

view solution

Exercise 7B

What is the purpose of the two lines of text in the HEAD of the page that begin with double slashes (// Assumes:... and // Results:...)? Would the page behave the same if these two lines of text were removed? Explain your answer.

view solution

Exercise 7C

Complete the definition of the Triangulate function, which accesses the lengths of the two sides entered in the text boxes and uses them to calculate the length of the third side (the hypotenuse). It also calculates the perimeter of the triangle (the sum of all three side lengths) and displays both values in the page. For example, if the user entered 3 and 4 in the text boxes, clicking the button should display the following message: The hypotenuse is 5, giving a perimeter of 12.

view solution

The next two exercises refer to the following HTML document, which could be used by a person to calculate the "body mass index" of a patient. The Center for Disease Control (CDC) defines body mass index (BMI) using the following formula: BMI = (weight in kilograms) / (height in meters)2.

<!doctype html> <html> <head> <title>Body Mass Index</title> <script type="text/javascript"> function ShowBMI() // Assumes: weightBox contains the person's weight in kilograms, // heightBox contains the person's height in centimeters (note: 1 m = 100 cm) // Results: computes body mass index and displays it in outputDiv { // CODE TO BE COMPLETED IN EXERCISE 7E } </script> </head> <body> <h1 style="text-align:center">Body Mass Index<br>(using the CDC Formula)</h1> <p> Your weight (kg): <input type="text" id="weightBox" size=8 value=74> <br> Your height (cm): <input type="text" id="heightBox" size=8 value=180> </p> <input type="button" value="Calculate" onclick="ShowBMI();"> <hr> <div id="outputDiv"></div> </body> </html>

Exercise 7D

Draw a picture of the Web page that would be displayed when this HTML document is loaded. Your drawing should clearly show the layout of the page elements, along with any text, labels, and default values, as they would initially appear in the page.

view solution

Exercise 7E

Complete the definition of the ShowBMI function, which accesses the weight and height values entered in the text boxes and uses them to calculate the body mass index using the CDC formula. The calculated BMI should be displayed in the outputDiv page division in a message of the form: Your body mass index is XXX.

view solution


Chapter 9

The next four exercises refer to the following HTML document, which could be used by a person to test whether they have ESP. You may assume that the following images are stored in the same folder as this page: mystery.gif (a question mark), number1.gif, number2.gif, and number3.gif (images of the digits 1, 2, and 3, resp.).

<!doctype html> <html> <head> <title> ESP </title> <script type="text/javascript"> function Picker() { num = Math.floor(Math.random()*3)+1; imgName = "number" + num + ".gif"; document.getElementById('numImg').src = imgName; } </script> </head> <body> <div style="text-align:center"> <h1>Do-it-yourself ESP Test</h1> <p> Think of a number between 1 and 3. <br> <input type="button" value="Click to see if you guessed correctly" onclick="Picker();"> </p> <img id="numImg" src="mystery.gif" alt="random number"> <div id="outputDiv">Do you have ESP?</div> </div> </body> </html>

Exercise 9A

Draw a picture of the Web page that would be displayed when this HTML document is loaded. Your drawing should clearly show the layout of the page elements, along with any text, labels, and default values, as they would initially appear in the page.

view solution

Exercise 9B

What (if anything) changes in the page when the user clicks on the button? Is the behavior the same each click? Explain your answer.

view solution

Exercise 9C

Modify the page so that it selects its random number from the range 1-9 (instead of 1-3). You may assume that image files number4.gif through number9.gif exist in the same folder.

view solution

Exercise 9D

Augment the above page so that, in addition to its current behavior, a message also appears in outputDiv (replacing any text already there). The message should be of the form The number was X. Did you guess it? where X is the number selected by the page.

view solution


Chapter 11

Exercise 11A

Consider the following function that takes two numbers as inputs:
function Compare(a, b) // Assumes: a and b are numbers // Returns: a message based on the values of a and b { var message; message = '['; if (a < b) { message = message + 'foo'; if (2*a >= b) { message = message + 'bar'; } } else if (a > b) { message = message + 'biz'; } message = message + ']'; return message; }

What value would be returned by each of the following function calls?
  • Compare(8, 5)
  • Compare(5, 8)
  • Compare(5, 5)
  • Compare(5, 20)

view solution

Exercise 11B

Design and implement a Web page with three text boxes and a button. When the user clicks the button, the page should display a message identifying whether any of the box contents are identical. The three possible message are 'All values are unique.', 'Two of the three match.', or 'All three are the same.'

view solution

Exercise 11C

Design and implement a Web page that contains a single button. When the user clicks the button, the page should simulate flipping two coins and display the results, e.g., You flipped HEADS and TAILS. If the two flips are identical, then the message should identify this, e.g., You flipped TAILS and TAILS - they match!

view solution

Exercise 11D

Add a counter to your page from Exercise 11C that keeps track of the number of flip matches. Initially, this counter should be 0, and it should be incremented each time matching flips are obtained.

view solution


Chapter 13

Exercise 13A

Consider the following function that takes a single number as input:
function Loopy(number) // Assumes: number is a positive number // Returns: a message based on number { var message; message = ''; while (number > 0) { message = (number % 2) + message; number = Math.floor(number / 2); } return message; }

What value would be returned by each of the following function calls?
  • Loopy(0)
  • Loopy(1)
  • Loopy(4)
  • Loopy(11)

view solution

Exercise 13B

Design and implement a Web page with two text boxes (which are to contain positive integers) and a button. When the user clicks the button, the page should display all of the integers in the range 1 to 100 that are divisible by the number in the first box, but not divisible by the number in the second box. For example, if the boxes contained 5 and 10, then the page should display 5, 15, 25, 35, ..., 95.

view solution

Exercise 13C

Modify your page from Exercise 13B so that it also displays a count of how many numbers were displayed. For example, 10 numbers are divisible by 5 but not 10.

view solution


Chapter 15

Exercise 15A

Consider the following function that takes a single string as input:
function Process(word) // Assumes: word is a string // Returns: a string based on word { var i, ch, message; message = 'X'; i = 0; while (i < word.length) { ch = word.charAt(i); message = ch + message + ch; i = i + 1; } return message; }

What value would be returned by each of the following function calls?
  • Process('')
  • Process('a')
  • Process('ab')
  • Process('1234')

view solution

Exercise 15B

Consider the page from Exercise 15A. What would happen if the statement i = i + 1; were missing from this code? Would the page still load correctly? Would it behave the same when the button was clicked?

view solution

Exercise 15C

Design and implement a page that contains a text area and button. When the user clicks on the button, any text in the text area is analyzed and statistics displayed in the page. The page should display the number of (non-space) characters in the text area, the number of sentences, and the average number of (non-space) characters per sentence. For simplicity, we will consider any occurrence of a period, question mark, or exclamation mark to denote the end of a sentence.

view solution


Chapter 17

Exercise 17A

Consider the following array assignment:
arr = [ 27, 13.0, 'foo', [1, 2, 3], 'booboo'];

To what value would each of the following expressions evaluate?
  • arr.length
  • arr[1]
  • arr[arr.length-1]
  • arr[3][0]
  • arr[4].length

view solution

Exercise 17B

Modify your text statistics page from Exercise 15C so that it also displays the number of words in the text area and the average number of words per sentence. In order to accomplish this, you will need to split the text into individual words using the split method. This will also allow for a more accurate count of the number of sentences. A period, exclamation mark, or question mark should only denote a sentence if it appears at the end of a word.

view solution



Solutions to Practice Exercises


Exercise 2A


Exercise 2B

These are comment tags. They are there to document the page, in this case by displaying the file name and a short description. Comments are ignored by the browser, so removing them would not change the appearance of the page in the browser.


Exercise 2C

Since the SRC is assigned a relative address (just the file name omaha.jpg, without an http:// prefix), it is assumed to be in the same directory/folder as the Web page. If the image file is not found, then the browser will display a broken image icon. Some broswers may also display the ALT text, Photo of Omaha Skyline, with the icon.


Exercise 2D

When the user clicks on the link, the browser will take them to the Wikipedia site for Omaha (whose address is http://en.wikipedia.org/wiki/Omaha,_Nebraska). That is, the page currently displayed in the browser will be replaced by the Wikipedia page. If the computer was not connected to the Internet, the browser would display an error page, with a message stating that no connection was found.


Exercise 4A


Exercise 4B

When a button is clicked, each ??? in the page would be replaced by the corresponding animal and sound. For example, if the user clicks on the Cow button, then the message would read The cow goes moo. Likewise, if they click on the Horse button, the message would read The horse goes neigh.


Exercise 4C

The page would still load the same, displaying the buttons and text as before. When the button is clicked, however, it would cause a JavaScript error, with the resulting error message (in the Error Console) complaining that the specified element is "null" or "not found.". The current contents of the animalSpan would remain unchanged.


Exercise 4D

The paragraph within the BODY should be changed as follows:
<p> <img id="animalImg" src="mystery.gif" alt="animal image"> <br> <input type="button" value="Cow" onclick="document.getElementById('animalSpan').innerHTML='cow'; document.getElementById('soundSpan').innerHTML='moo'; document.getElementById('animalImg').src='cow.jpg';"> <input type="button" value="Horse" onclick="document.getElementById('animalSpan').innerHTML='horse'; document.getElementById('soundSpan').innerHTML='neigh'; document.getElementById('animalImg').src='horse.jpg';"> </p>


Exercise 5A

The scale amount will be an integer ranging from 0 to 4. The smallest value obtainable from Math.random() is 0, so Math.floor(0*5) = Math.floor(0) = 0. The largest value obtainable from Math.random() is 0.9999... (almost, but not quite 1), so Math.floor(0.999...*5) = Math.floor(4.999...) = 4.


Exercise 5B

Whenever you access the VALUE attribute of a text box, the box contents are treated as a string. Thus, if the user entered 90, it would be accessed as '90'. Then, when you add that string value to a number, e.g., '90' + 3, the number is converted into a string an concatenation occurs, e.g., '90' + 3 → '90' + '3' → '903'. To avoid this conversion, you should always use parseFloat to convert the value in the box into a number. In this case:
    grade = parseFloat(document.getElementById('gradeBox').value);


Exercise 5C


Exercise 5D

The quote in the page would be replaced by a message that included the animal name. For example, if the user entered aardvark, then the message would read I like aardvarks too!


Exercise 5E

The IMG element within the BODY should be changed as follows:
<input type="button" value="Submit your pick" onclick="animal = document.getElementById('animalBox').value; document.getElementById('outputDiv').innerHTML = 'I like ' + animal + 's too!'; document.getElementById('animalImg').src = animal + '.jpg';">


Exercise 5F

Browsers differ in how they would handle this error. Safari generates an error message, stating that the "resource failed to load", and the image is replaced by the broken image icon. Firefox simply ignores the error, leaving the image in the page unchanged.


Exercise 7A


Exercise 7B

These are JavaScript comments. They are there to document the behavior of the function. Any text preceded by double-slashes is ignored by the JavaScript interpreter, so removing these lines would not change the behavior of the page.


Exercise 7C

function Triangulate() // Assumes: aBox and bBox contain the lengths of the two sides of a right triangle // Results: computes and displays the 3rd side (the hypotenuse) & perimeter in outputDiv { a = parseFloat(document.getElementById('aBox').value); b = parseFloat(document.getElementById('bBox').value); c = Math.sqrt(a*a + b*b); perimeter = a + b + c; document.getElementById('outputDiv').innerHTML = 'The hypotenuse is ' + c + ', giving a perimeter of ' + perimeter + '.'; }


Exercise 7D


Exercise 7E

function ShowBMI() // Assumes: weightBox contains the person's weight in kilograms, // heightBox contains the person's height in centimeters (note: 1 m = 100 cm) // Results: computes body mass index and displays it in outputDiv { kg = parseFloat(document.getElementById('weightBox').value); cm = parseFloat(document.getElementById('heightBox').value); m = cm / 100; bmi = kg/Math.pow(m, 2); document.getElementById('outputDiv').innerHTML = 'Your body mass index is ' + bmi; }


Exercise 9A


Exercise 9B

A random integer between 1 and 3 is selected, and the image (numImg) is changed to display the corresponding number image (number1.gif, number2.gif, or number3.gif). The behavior is the same each time the button is clicked, but the number selected each time will vary.


Exercise 9C

Simply change the 3 in the expression to 9 (and also change the upper limit in the BODY of the page).
     num = Math.floor(Math.random()*9)+1;


Exercise 9D

Add the following assignment at the end of the function:
document.getElementById('outputDiv').innerHTML = 'The number was ' + num + '. Did you guess it?';


Exercise 11A

  • Compare(8, 5) → '[biz]'
  • Compare(5, 8) → '[foobar]'
  • Compare(5, 5) → '[]'
  • Compare(5, 20) → '[foo]'


Exercise 11B

<!doctype html> <html> <head> <title> Classification Page </title> <script type="text/javascript"> function Classify() // Assumes: box1, box2, and box3 are in the page // Results: displays a message based on the values in the boxes { var val1, val2, val3; val1 = document.getElementById('box1').value; val2 = document.getElementById('box2').value; val3 = document.getElementById('box3').value; if (val1 == val2 && val2 == val3) { document.getElementById('outputDiv').innerHTML = 'All three are the same.'; } else if (val1 == val2 || val1 == val3 || val2 == val3) { document.getElementById('outputDiv').innerHTML = 'Two of the three match.'; } else { document.getElementById('outputDiv').innerHTML = 'All values are unique.'; } } </script> </head> <body> <p> <input type="text" id="box1" size=12 value=""> <br> <input type="text" id="box2" size=12 value=""> <br> <input type="text" id="box3" size=12 value=""> </p> <input type="button" value="Click for Message" onclick="Classify();"> <div id='outputDiv'></div> </body> </html>


Exercise 11C

<!doctype html> <html> <head> <title> Coin Flip Page </title> <script type="text/javascript" src="http://balance3e.com/random.js"></script> <script type="text/javascript"> function Flipper() // Assumes: outputDiv is available for output // Results: displays a message based on the values in the boxes { var flip1, flip2, message; flip1 = RandomOneOf(['HEADS', 'TAILS']); flip2 = RandomOneOf(['HEADS', 'TAILS']); message = 'You flipped ' + flip1 + ' and ' + flip2; if (flip1 == flip2) { message = message + ' - they match!' } document.getElementById('outputDiv').innerHTML = message; } </script> </head> <body> <input type="button" value="Click for Flips" onclick="Flipper();"> <div id='outputDiv'></div> </body> </html>


Exercise 11D

// Add at bottom of BODY (before the </body> tag) <p> Number of matches: <span id="matchSpan">0</span> </p> // Add at end of IF statement (before the right curly-brace) document.getElementById('matchSpan').innerHTML = parseFloat(document.getElementById('matchSpan').innerHTML)+1;


Exercise 13A

  • Loopy(0) → ''
  • Loopy(1) → '1'
  • Loopy(4) → '100'
  • Loopy(11) → '1011'


Exercise 13B

<!doctype html> <html> <head> <title> While Demo Page </title> <script type="text/javascript"> function DisplayNums() // Assumes: divBox and nondivBox contain positive integers // Results: displays numbers from 1 to 100 that are divisible by divBox value // but not divisible by nondivBox value { var i, divVal, nondivVal; divVal = parseFloat(document.getElementById('divBox').value); nondivVal = parseFloat(document.getElementById('nondivBox').value); document.getElementById('outputDiv').innerHTML = ''; i = 1; while (i <= 100) { if (i % divVal == 0 && i % nondivVal != 0) { document.getElementById('outputDiv').innerHTML = document.getElementById('outputDiv').innerHTML + '<br>' + i; } i = i + 1; } } </script> </head> <body> <p> Display all integers between 1 and 100 that are divisible by: <input type="text" id="divBox" size=6 value=""> but not divisible by <input type="text" id="nondivBox" size=6 value="">. </p> <input type="button" value="Click to Display" onclick="DisplayNums();"> <br> <div id="outputDiv"></div> </body> </html>


Exercise 13C

<!doctype html> <html> <head> <title> While Demo Page </title> <script type="text/javascript"> function DisplayNums() // Assumes: divBox and nondivBox contain positive integers // Results: displays numbers from 1 to 100 that are divisible by divBox value // but not divisible by nondivBox value { var i, divVal, nondivVal, count; divVal = parseFloat(document.getElementById('divBox').value); nondivVal = parseFloat(document.getElementById('nondivBox').value); document.getElementById('outputDiv').innerHTML = ''; count = 0; i = 1; while (i <= 100) { if (i % divVal == 0 && i % nondivVal != 0) { document.getElementById('outputDiv').innerHTML = document.getElementById('outputDiv').innerHTML + '<br>' + i; count = count + 1; } i = i + 1; } document.getElementById('outputDiv').innerHTML = document.getElementById('outputDiv').innerHTML + '<br>' + count + ' numbers are divisible by ' + divVal + ' but not ' + nondivVal + '.'; } </script> </head> <body> <p> Display all integers between 1 and 100 that are divisible by: <input type="text" id="divBox" size=6 value=""> but not divisible by <input type="text" id="nondivBox" size=6 value="">. </p> <input type="button" value="Click to Display" onclick="DisplayNums();"> <br> <div id="outputDiv"></div> </body> </html>


Exercise 15A

  • Process('') → 'X'
  • Process('a') → 'aXa'
  • Process('ab') → 'baXab'
  • Process('1234') → '4321X1234'


Exercise 15B

Without this statement, an infinite loop would occur. The page would still load, but a click of the button would initiate an infinite loop, processing the first number in the sequence (1) over and over. If 1 meets the desired properties, then it will be printed endlessly; if not, then no output would appear but the page would be stuck.


Exercise 15C

<!doctype html> <html> <head> <title> Text Stats Page </title> <script type="text/javascript"> function GetStats() // Assumes: contentArea contains text // Results: displays stats on the contents in outputDiv { var text, numChars, numSentences, i, ch; text = document.getElementById('contentArea').value; numChars = 0; numSentences = 0; i = 0; while (i < text.length) { ch = text.charAt(i); if (ch != ' ') { numChars = numChars + 1; if (ch == '.' || ch == '?' || ch == '!') { numSentences = numSentences + 1; } } i = i + 1; } document.getElementById('outputDiv').innerHTML = 'Number of (non-space) characters: ' + numChars + '<br>' + 'Number of sentences: ' + numSentences + '<br>' + 'Characters per sentence: ' + (numChars/numSentences); } </script> </head> <body> <p> Enter text here: <br> <textarea id="contentArea" rows=10 cols=40></textarea> </p> <input type="button" value="Click for Message" onclick="GetStats();"> <br> <div id="outputDiv"></div> </body> </html>


Exercise 17A

  • arr.length → 5
  • arr[1] → 13.0
  • arr[arr.length-1] → 'booboo'
  • arr[3][0] → 1
  • arr[4].length → 6


Exercise 17B

<!doctype html> <html> <head> <title> Text Stats Page </title> <script type="text/javascript"> function GetStats() // Assumes: contentArea contains text // Results: displays stats on the contents in putputDiv { var text, numChars, numSentences, words, w, i; text = document.getElementById('contentArea').value; words = text.split(/[ \t]+/); numChars = 0; numSentences = 0; i = 0; while (i < words.length) { w = words[i]; numChars = numChars + w.length; if (w[w.length-1] == '.' || w[w.length-1] == '?' || w[w.length-1] == '!') { numSentences = numSentences + 1; } i = i + 1; } document.getElementById('outputDiv').innerHTML = 'Number of (non-space) characters: ' + numChars + '<br>' + 'Number of words: ' + words.length + '<br>' + 'Number of sentences: ' + numSentences + '<br>' + 'Characters per sentence: ' + (numChars/numSentences) + '<br>' + 'Words per sentence: ' + (words.length/numSentences); } </script> </head> <body> <p> Enter text here: <br> <textarea id="contentArea" rows=10 cols=40></textarea> </p> <input type="button" value="Click for Message" onclick="GetStats();"> <br> <div id="outputDiv"></div> </body> </html>