JavaScript Control Structures II

JavaScript: Control Structures II
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
whileCounter.html
<!-- WhileCounter.html
-->
<!-- Counter-Controlled Repetition -->
<html xmlns = "http://www.w3.org/1999/xhtml">
The while loop will
<head>
value of counter is
<title>Counter-Controlled Repetition</title>
continue until the
greater than 7.
<script type = "text/javascript">
<!-var counter = 1;
// initialization
while ( counter <= 7 ) {
// repetition condition
document.writeln( "<p style = \"font-size: " +
counter + "ex\">XHTML font size " + counter +
"ex</p>" );
++counter;
// increment
}
// -->
</script>
Increment the counter.
</head><body></body>
</html>
2
Program Output
3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
ForCounter.html
<!-- ForCounter.html
-->
<!-- Counter-Controlled Repetition with for structure -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Counter-Controlled
Repetition</title>
Initialization
Repetition condition
<script type = "text/javascript">
Incrementing
<!-// Initialization, repetition condition and
// incrementing are all included in the for
// structure header.
for ( var counter = 1; counter <= 7; ++counter )
document.writeln( "<p style = \"font-size: " +
counter + "ex\">XHTML font size " + counter +
"ex</p>" );
// -->
</script>
</head><body></body>
</html>
4
Program Output
5
For Repetition Structure
for keyword
Control variable
name
Final value of control variable
for which the condition is true
for ( var counter = 1 ; counter <= 7 ; ++counter )
Initial value of control variable
Increment of control variable
Loop-continuation condition
Components of a typical for structure header.
6
Examples Using the for Structure
Establish
initial value
of control
variable.
var counter = 1
counter <= 7
false
Determine
if final value
of control
variable
has been
reached.
true
document.writeln(
"<p style=\"font-size: "
+ counter +
"ex\">XHTML font size " +
counter + "ex</p>" );
++counter
Increment
the control
variable.
Body of loop
(this may be many
statements)
Flowcharting a typical for repetition structure.
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Sum.html
<!-- Sum.html
-->
<!-- Using the for repetition structure -->
<html xmlns = "http://www.w3.org/1999/xhtml">
The for loop will continue until
<head>
of number is greater than 100.
<title>Sum the Even Integers from 2 to 100</title>
<script type = "text/javascript">
Initialization.
<!-Repetition
var sum = 0;
the value
condition.
Incrementing.
for ( var number = 2; number <= 100; number += 2 )
sum += number;
document.writeln( "The sum of the even integers " +
"from 2 to 100 is " + sum );
// -->
</script>
</head><body></body>
</html>
Program Output
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Interest.html
<!-- interest.html
-->
<!-- Using the for repetition structure -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Calculating Compound Interest</title>
Opening table element.
<script type = "text/javascript">
<!-var amount, principal = 1000.0, rate = .05;
document.writeln(
"<table border = \"1\" width = \"100%\">" );
document.writeln(
"<caption>Calculating Compound Interest</caption>" );
document.writeln(
iteration of the for loop
"<thead><tr><th alignEach
= \"left\">Year</th>"
); creates a
document.writeln(
table row listing the year of the loan and
"<th align = \"left\">Amount on deposit</th>" );
the amount.
document.writeln( "</tr></thead>" );
for ( var year = 1; year <= 10; ++year ) {
amount = principal * Math.pow( 1.0 + rate, year );
document.writeln( "<tbody><tr><td>" + year +
"</td><td>" + Math.round( amount * 100 ) / 100 +
"</td></tr>" );
}
document.writeln( "</tbody></table>" );
// -->
</script>
9
36
37
38
</head><body></body>
</html>
Interest.html
Program Output
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
SwitchTest.html
<!-- SwitchTest.html
-->
<!-- Using the switch structure -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Switching between
List
Formats</title>
Variable XHTML
choice
is given
the value input
by the
user in the prompt dialog.
<script type = "text/javascript">
<!-var choice,
// user’s choice
The
of choice
is evaluated
against
startTag,
// value
starting
list item
tag
endTag,
// ending
list item
each
of the values
of thetag
case labels.
validInput = true, // indicates if input is valid
listType;
// list type as a string
choice = window.prompt( "Select a list style:\n" +
"1 (bullet), 2 (numbered), 3 (lettered)", "1" );
The break statement causes program control
switch ( choice ) { to proceed with the first statement after the
case "1":
switch structure.
startTag = "<ul>";
endTag =
listType
break;
case "2":
startTag
endTag =
listType
break;
"</ul>";
= "<h1>Bullet List</h1>";
= "<ol>";
"</ol>";
= "<h1>Ordered List: Numbered</h1>";
11
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
case "3":
startTag = "<ol type = \"A\">";
endTag = "</ol>";
listType = "<h1>Ordered List: Lettered</h1>";
break;
default:
validInput = false;
}
SwitchTest.html
If none of the cases match, variable
validInput is set to false.
if ( validInput == true ) {
document.writeln( listType + startTag );
for ( var i = 1; i <= 3; ++i )
If the user input a valid value, the list is
document.writeln( "<li>List item " + i + "</li>" );
created.
document.writeln( endTag );
}
else
document.writeln( "Invalid choice: " + choice );
// -->
</script>
Otherwise, the message “Invalid
in the browser.
</head>
choice” is displayed
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
12
Program Output
13
Program Output
14
switch Multiple-Selection Structure
true
casea
casea ac tion(s)
break
caseb ac tion(s)
break
casez ac tion(s)
break
false
true
caseb
false
.
.
.
true
casez
false
defaulta c tion(s)
switch multiple-selection structure.
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
DoWhileTest.html
<!-- DoWhileTest.html
-->
<!-- Using the do/while structure -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using the do/while Repetition Structure</title>
<script type = "text/javascript">
Each iteration of the do/while loop
<!-a line of text with a header
var counter = writes
1;
element to the XHTML document.
do {
document.writeln( "<h" + counter
">This
is the
" +value
The loop+stops
when
"an h" + counter + " level head" + "</h" +
counter is greater than 6.
counter + ">" );
of
++counter;
} while ( counter <= 6 );
// -->
</script>
</head><body></body>
</html>
16
Program Output
17
do/while Repetition Structure
action(s)
condition
true
false
Flowcharting the do/while repetition structure.
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- BreakTest.html
<!-- Using the break statement
BreakTest.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
When the value of variable count equals 5,
<title>
Using the break Statement
in astatement
for Structure
the break
causes program control
</title>
to
proceed to the first line outside the for loop.
<script type = "text/javascript">
<!-for ( var count = 1; count <= 10; ++count ) {
if ( count == 5 )
break; // break loop only if count == 5
document.writeln( "Count is: " + count + "<br />" );
}
document.writeln(
"Broke out of loop at count = " + count );
// -->
</script>
</head><body></body>
</html>
19
Program Output
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- ContinueTest.html
<!-- Using the break statement
ContinueTest.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
When the value of variable count equals 5, the
<title>
continue
causes program control to
Using the continue Statement
in statement
a for Structure
</title>
proceed to the next iteration of the for loop.
<script type = "text/javascript">
<!-for ( var count = 1; count <= 10; ++count ) {
if ( count == 5 )
continue; // skip remaining code in loop
// only if count == 5
document.writeln( "Count is: " + count + "<br />" );
}
document.writeln( "Used continue to skip printing 5" );
// -->
</script>
</head><body></body>
</html>
21
Program Output
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
BreakLabelTest.htm
<!-- BreakLabelTest.html
-->
<!-- Using the break statement with a Label -->
stop is the label for the break statement.
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using the break Statement with a Label</title>
When the break statement is encountered, program
<script type = "text/javascript">
<!-control proceeds to the first line outside the stop block
stop: {
// labeled compound
statement
and not just
the for loop where the statement is found.
for ( var row = 1; row <= 10; ++row ) {
for ( var column = 1; column <= 5 ; ++column ) {
if ( row == 5 )
break stop; // jump to end of stop block
document.write( "* " );
}
document.writeln( "<br />" );
}
// the following line is skipped
document.writeln( "This line should not print" );
}
23
31
32
33
34
35
36
document.writeln( "End of script" );
// -->
</script>
</head><body></body>
</html>
BreakLabelTest.htm
Program Output
24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- ContinueLabelTest.html
<!-- Using the continue statement
ContinueLabelTest.htm
-->
-->
nextRow is the label for the continue
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using the continue Statement with a Label</title>
statement.
If the value of variable column is greater than the
statement
<script type = "text/javascript">
value of variable row, the continue
<!-nextRow:
// target label of
continue
statement
causes
the next
interation of the loop.
for ( var row = 1; row <= 5; ++row ) {
document.writeln( "<br />" );
for ( var column = 1; column <= 10; ++column ) {
If the continue statement is performed,
the string “* “
if ( column > row )
method write does not print
continue nextRow; // next iteration of
in the
// XHTML
labeled document.
loop
document.write( "* " );
}
}
// -->
</script>
</head><body></body>
</html>
25
Program Output
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- LogicalOperators.html
<!-- Demonstrating Logical Operators
LogicalOperators.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Demonstrating the Logical Operators</title>
Each expression will
<script type = "text/javascript">
<!-or false using the
document.writeln(
AND.
"<table border = \"1\" width = \"100%\">"
);
document.writeln(
"<caption>Demonstrating Logical " +
"Operators</caption" );
evaluate to true
rules of logical
Each expression will evaluate to
true or false using the rules of
logical OR.
document.writeln(
"<tr><td width = \"25%\">Logical AND (&&)</td>" +
"<td>false && false: " + ( false && false ) +
"<br />false && true: " + ( false && true ) +
"<br />true && false: " + ( true && false ) +
"<br />true && true: " + ( true && true ) +
"</td>" );
document.writeln(
"<tr><td width = \"25%\">Logical OR (||)</td>" +
"<td>false || false: " + ( false || false ) +
"<br />false || true: " + ( false || true ) +
"<br />true || false: " + ( true || false ) +
"<br />true || true: " + ( true || true ) +
"</td>" );
27
36
37
38
39
40
41
42
43
44
45
46
47
document.writeln(
"<tr><td width = \"25%\">Logical NOT (!)</td>" +
"<td>!false: " + ( !false ) +
"<br />!true: " + ( !true ) + "</td>" );
document.writeln( "</table>" );
// -->
</script>
LogicalOperators.html
These expressions demonstrate the
use of logical NOT.
</head><body></body>
</html>
Program Output
28
Summary of Structured Programming
Rep etition
Se lectio n
whilestruc ture
struc ture
i
f
/
e
l
s
e
(d ouble se lec tion)
T
T
Seq uenc e
struc ture
i
f
(sing le selec tio n)
F
T
F
F
do/whilestruc ture
.
.
.
s
witchstruc ture
(multiple se lec tion)
break
T
break
T
F
T
F
forstruc ture
F
.
.
.
break
T
F
T
F
JavaScript’s single-entry/single-exit sequence, selection and repetition structures.
29
Summary of Structured Programming
Unstructured flowchart.
30
JavaScript: Functions
31
Program Modules in JavaScript
main
worker1
worker4
worker2
worker3
worker5
Hierarchical boss-function/worker-function relationship.
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- SquareInt.html
<!-- Square function
SquareInt.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>A Programmer-Defined square Function</title>
<script type = "text/javascript">
<!-Calling function square and
document.writeln(
"<h1>Square the numbers from 1 to 10</h1>" );
passing it the value of x.
// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
document.writeln( "The square of " + x + " is " +
square( x ) + "<br />" );
// The following square Variable
function's
body
executed
y gets
theis
value
of variable
// only when the function is explicitly called.
x.
// square function definition
function square( y )
{
return y * y;
}
// -->
The return statement
</script>
</head><body></body>
</html>
passes the value of y * y
back to the calling function.
33
Program Output
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- maximum.html
<!-- Maximum function
Maximum.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Finding the Maximum of Three
PromptValues</title>
for the user to input
three integers.
<script type = "text/javascript">
<!-var input1 =
window.prompt( "Enter first number", "0" );
var input2 =
Call function maximum and pass it the value
window.prompt( "Enter second number", "0" );
variables value1, value2 and value3.
var input3 =
window.prompt( "Enter third number", "0" );
of
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 Variables
);
var value3 = parseFloat( input3 );
x, y and z get the value of variables
value1, value2 and value3, respectively.
var maxValue = maximum( value1, value2, value3 );
document.writeln( "First number: " + value1 +
"<br />Second number: " + value2 +
"<br />Third number: " + value3Method
+
max
"<br />Maximum is: " + maxValue );
returns the larger of the two
integers passed to it.
// maximum method definition (called from line 25)
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
35
36
37
38
39
40
41
42
43
44
}
// -->
</script>
Maximum.html
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Program Output
36
Program Output
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
RandomInt.html
<!-- RandomInt.html
-->
<!-- Demonstrating the Random method -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Shifted and Scaled Random Integers</title>
<script type = "text/javascript">
The for loop creates
<!-var value;
4 rows with 5 cells of a table.
Method floor rounds the number
document.writeln(
"<table border = \"1\" width
= \"50%\">"
); random down.
generated
by method
document.writeln(
"<caption>Random Numbers</caption><tr>" );Each cell is populated
with a
random number generated by
method
random.
);
for ( var i = 1; i <= 20; i++ ) {
value = Math.floor( 1 + Math.random() * 6
document.writeln( "<td>" + value + "</td>" );
// write end and start <tr> tags when
// i is a multiple of 5 and not 20
if ( i % 5 == 0 && i != 20 )
document.writeln( "</tr><tr>" );
}
document.writeln( "</tr></table>" );
// -->
</script>
</head>
38
36
37
38
39
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
RandomInt.html
Program Output
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
RollD.html
<!-- RollD.html
-->
<!-- Rolling a Six-Sided Die -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Roll a Six-Sided Die 6000 Times</title>
This expression uses method random to
generate a random number between 1 and 6.
<script type = "text/javascript">
<!-var frequency1 = 0, frequency2 = 0,
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0, face;
When the controlling expression, face,
// summarize results
for ( var roll = 1; roll <= 6000;
++roll
) { label, the respective
matches
a case
face = Math.floor( 1 + Math.random()
* 6 variable
);
frequency
is incremented.
switch ( face ) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
40
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
RollD.html
The results of the dice being rolled 600 times
are displayed in a table.
document.writeln( "<table border = \"1\"" +
"width = \"50%\">" );
document.writeln( "<thead><th>Face</th>" +
"<th>Frequency<th></thead>" );
document.writeln( "<tbody><tr><td>1</td><td>" +
frequency1 + "</td></tr>" );
document.writeln( "<tr><td>2</td><td>" + frequency2
"</td></tr>" );
document.writeln( "<tr><td>3</td><td>" + frequency3
"</td></tr>" );
document.writeln( "<tr><td>4</td><td>" + frequency4
"</td></tr>" );
document.writeln( "<tr><td>5</td><td>" + frequency5
"</td></tr>" );
document.writeln( "<tr><td>6</td><td>" + frequency6
"</td></tr></tbody></table>" );
// -->
</script>
+
+
+
+
+
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
41
Program Output
42
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- Craps.html
<!-- Craps Program
Craps.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Program that Simulates the Game of Craps</title>
<script type = "text/javascript">
<!-// variables used to test the state of the game
var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
// other variables used in program
var firstRoll = true,
// true if first roll
sumOfDice = 0,
// sum of the dice
If
the
value
of firstRoll is true,
myPoint = 0, // point if no win/loss on first roll
function rollDice
is called.
gameStatus = CONTINUE_ROLLING;
// game not
over yet
then
// process one roll of the dice
If function rollDice returns a value of
function play()
{
7 or 11, theplayer wins and the break
if ( firstRoll ) {
// first roll of the dice
statement causes program control
sumOfDice = rollDice();
proceeds to the first line after the switch
structure.
switch ( sumOfDice ) {
case 7: case 11:
// win on first roll
gameStatus = WON;
// clear point field
document.craps.point.value = "";
break;
case 2: case 3: case 12: // lose on first roll
43
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
gameStatus = LOST;
Craps.html
// clear point field
document.craps.point.value = "";
break;
default:
// remember point
If
function rollDice retursn a 2, 3 or 12, the
gameStatus = CONTINUE_ROLLING;
myPoint = sumOfDice;
player loses and the break statement causes
document.craps.point.value = myPoint;
control to proceed to first line after the switch
firstRoll = false;
}
structure.
}
else {
sumOfDice = rollDice();
if ( sumOfDice == myPoint ) // win by making point
gameStatus = WON;
else
If the value returned by function rollDice
if ( sumOfDice == 7 )
// lose by rolling 7
equals the value of variable myPoint, the player
gameStatus = LOST;
wins because the point has been reached.
}
if ( gameStatus == CONTINUE_ROLLING )
window.status = "Roll again";
If the values returned by function
else {
rollDice equals 7, the player loses.
if ( gameStatus == WON )
window.status = "Player wins. " +
"Click Roll Dice to play again.";
else
window.status = "Player loses.
" + method status displays a
window
"Click Roll Dice to play again.";
message in the status bar of the browser.
firstRoll = true;
}
}
44
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// roll the dice
function rollDice()
{
var die1, die2, workSum;
Craps.html
die1 = Math.floor( 1 +Function
Math.random()
* 6 is
);called to simulate
rollDice
die2 = Math.floor( 1 + Math.random() * 6 );
the rolling of two dice on the craps table.
workSum = die1 + die2;
document.craps.firstDie.value = die1;
document.craps.secondDie.value Methods
= die2; random and floor
document.craps.sum.value = workSum;
generate the values for the two
are used to
dice.
return workSum;
}
// -->
</script>
Referencing the names of form elements
in the XHTML document, the vlaues of
the dice are placed in their respective
form fields.
</head>
<body>
<form name = "craps" action = "">
<table border = "1">
<caption>Craps</caption>
<tr><td>Die 1</td>
<td><input name = "firstDie" type = "text" />
</td></tr>
<tr><td>Die 2</td>
<td><input name = "secondDie" type = "text" />
</td></tr>
<tr><td>Sum</td>
<td><input name = "sum" type = "text" />
</td></tr>
<tr><td>Point</td>
<td><input name = "point" type = "text" />
</td></tr>
45
106
107
108
109
110
111
<tr><td><input type = "button" value = "Roll Dice"
onclick = "play()" /></td></tr>
</table>
</form>
</body>
</html>
Craps.html
Program Output
text
A
XHTM L G UI
c om ponent
button
A
XHTM L G UI
c om ponent
Brow ser’ s
st at us ba r
46
Program Output
47
Program Output
48
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Scoping.html
<!-- scoping.html
-->
<!-- Local and Global Variables -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
To begin the
<title>A Scoping Example</title>
<script type = "text/javascript">
<!-var x = 1;
// global variable
Function
program, variable x is initialized to 1.
start changes the value of x to 5.
function start()
{
var x = 5;
// variable local to function start
document.writeln( "local x in start is " + x );
functionA();
functionB();
functionA();
functionB();
//
//
//
//
functionA
has local
x
Function
functionA
changes
functionB uses global variable x
functionA reinitializes local x
global variable x retains its value
the value of x to 25.
document.writeln(
"<p>local x in start is " + x + "</p>" );
}
function functionA()
{
var x = 25; // initialized each time
// functionA is called
49
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
document.writeln( "<p>local x in functionA is " +
x + " after entering functionA" );
++x;
document.writeln( "<br />local x in functionA is " +
x + " before exiting functionA" + "</p>" );
}
Scoping.html
The value of x is incremented.
function functionB()
{
document.writeln( "<p>global variable x is " + x +
" on entering functionB" );
x *= 10;
document.writeln( "<br />global variable x is " +
x + " on exiting functionB" + "</p>" );
}
// -->
Function functionB multiplies the value
</script>
of x by 10.
</head>
<body onload = "start()"></body>
</html>
50
Program Output
51
JavaScript Global Functions
Glob a l func tio n
De sc rip tio n
escape
This 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 (see Appendix
C, ASCII Character Set) are encoded in a hexadecimal format (see the Number Systems
appendix) that can be represented on all platforms.
eval
This function takes a string argument representing JavaScript code to execute. The JavaScript
interpreter evaluates the code and executes it when the eval function is called. This function
allows JavaScript code to be stored as strings and executed dynamically.
isFinite
This function takes a numeric argument and returns true if the value of the argument is not
NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise,
the function returns false.
isNaN
This function takes a numeric argument and returns true if the value of the argument is not a
number; otherwise, the function returns false. The function is commonly used with the return
value of parseInt or parseFloat to determine whether the result is a proper numeric
value.
Fig. 10.8
JavaScript g lob a l func tions.
52
JavaScript Global Functions
Glob a l func tio n
De sc rip tio n
parseFloat
This function takes a string argument and attempts to convert the beginning of the string into a
floating-point value. If the conversion is unsuccessful, the function returns NaN; otherwise, it
returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and
parseFloat( "123.45abc" ) returns the value 123.45).
parseInt
This function takes a string argument and attempts to convert the beginning of the string into
an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it
returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt(
"123abc" ) returns the integer value 123). This function takes an optional second
argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that
the first argument string is in binary format, base 8 indicates that the first argument string is
in octal format and base 16 indicates that the first argument string is in hexadecimal
format. See see the “Number Systems” appendix for more information on binary, octal and
hexadecimal numbers.
unescape
Fig. 10.8
This function takes a string as its argument and returns a string in which all characters
previously encoded with escape are decoded.
JavaScript g lob a l func tions.
53
Recursion
Final value = 120
5!
5!
5! = 5 * 24 = 120 is returned
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1!
1 returned
1
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
(a) Procession of recursive calls.
(b) Values returned from each recursive call.
Recursive evaluation of 5!.
54
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- FactorialTest.html
-->
<!-- Recursive factorial example
-->
FactorialTest.html
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Recursive Factorial Function</title>
Calling function factorial and
passing it the value of i.
<script language = "javascript">
document.writeln( "<h1>Factorials of 1 to 10</h1>" );
document.writeln(
"<table border = '1' width = '100%'>" );
for ( var i = 0; i <= 10; i++ )
document.writeln( "<tr><td>" + i + "!</td><td>" +
factorial( i ) + "</td></tr>" );
Variable number gets the value of variable i.
document.writeln( "</table>" );
// Recursive definition of function factorial
function factorial( number )
{
Call to function factorial and passing
if ( number <= 1 ) // base case
less than the current value of number.
return 1;
else
return number * factorial( number - 1 );
}
</script>
</head><body></body>
</html>
it 1
55
Program Output
56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- FibonacciTest.html
-->
<!-- Recursive Fibonacci example
-->
FibonacciTest.html
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Recursive Fibonacci Function</title>
<script language = "javascript">
Convert from a string to an integer the value the
user typed into the number text field.
// Event handler for button XHTML component in myForm
function getFibonacciValue()
Display the number the user
{
var value = parseInt(
status bar.
document.myForm.number.value );
window.status =
"Calculating Fibonacci number for " + value;
document.myForm.result.value = fibonacci( value );
window.status = "Done calculating Fibonacci number";
}
entered in the
// Recursive definition of The
function
status fibonacci
bar displays a message that the call
function fibonacci( n )
to function fibonacci is complete.
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
Test for base case (n equal to 1 or 0).
}
</script>
</head>
Two recursive calls are made if n is greater than
1.
57
35
36
37
38
39
40
41
42
43
44
45
46
<body>
<form name = "myForm">
<table border = "1">
<tr><td>Enter an integer</td>
<td><input name = "number" type = "text"></td>
<td><input type = "button" value = "Calculate"
onclick = "getFibonacciValue()"</tr>
<tr><td>Fibonacci value</td>
<td><input name = "result" type = "text"></td></tr>
</table>
</form></body>
</html>
FibonacciTest.html
Program Output
58
Program Output
59
Example Using Recursion: Fibonacci Series
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 )
return 1
return 1
return 0
Set of recursive calls to function fibonacci.
60
JavaScript: Arrays
61
Arrays
Name of array (Note
that all elements of
this array have the
same name, c)
Position number (index
or subscript) of the
element within array c
c[ 0 ]
-45
c[ 1 ]
6
c[ 2 ]
0
c[ 3 ]
72
c[ 4 ]
1543
c[ 5 ]
-89
c[ 6 ]
0
c[ 7 ]
62
c[ 8 ]
-3
c[ 9 ]
1
c[ 10 ]
6453
c[ 11 ]
78
A 12-element array.
62
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- InitArray.html
<!-- Initializing an Array
InitArray.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Initializing an Array</title>Array
n1 has five elements.
<script type = "text/javascript">
<!-Array n2 is an empty array.
// this function is called when the <body> element's
// onload event occurs
function initializeArrays()
The for loop initializes the elements
{
var n1 = new Array( 5 );
//
allocate
5-element
Array
their
subscript
numbers (0
to 4).
var n2 = new Array();
// allocate empty Array
in n1 to
// assign values to each element of Array n1
The for loop
five elements to Array n2 and
for ( var i = 0; i < n1.length;
++iadds
)
n1[ i ] = i;
initialize each element to its subscript number (0 to 4).
// create and initialize five-elements in Array n2
for ( i = 0; i < 5; ++i ) Each function displays the contents of
n2[ i ] = i;
respective Array in an XHTML table.
its
outputArray( "Array n1 contains", n1 );
outputArray( "Array n2 contains", n2 );
}
63
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// output "header" followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray( header, theArray )
{
document.writeln( "<h2>" + header + "</h2>" );
document.writeln( "<table border = \"1\" width =" +
"\"100%\">"
); time
The first
second
function
ouputArray
is
The
time
function
ouputArray
is called,
InitArray.html
called, variable
header
theof
of +
variable
header
gets thegets
value
“Array
document.writeln(
"<thead><th
width
=value
\"100\""
“Array
n2 contains”
and
variable
"align
=contains”
\"left\">Subscript</th>"
+
n1
and variable
theArray
gets
"<ththe
align
);
theArray
gets the value of n2.
value= of\"left\">Value</th></thead><tbody>"
n1.
for ( var i = 0; i < theArray.length; i++ )
document.writeln( "<tr><td>" + i + "</td><td>" +
theArray[ i ] + "</td></tr>" );
document.writeln( "</tbody></table>" );
}
// -->
</script>
</head><body onload = "initializeArrays()"></body>
</html>
64
Program Output
65
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
InitArray2.html
<!-- InitArray2.html
-->
<!-- Initializing an Array with a Declaration -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
Array integers1 is initialized using
<title>Initializing an Array with a Declaration</title>
an initializer list.
<script type = "text/javascript">
Two values are not supplied for integer2,
<!-function start()
which will be displayed as undefined.
{
// Initializer list specifies number of elements and
// value for each element.
var colors = new Array( "cyan", "magenta",
"yellow", "black" );
var integers1 = [ 2, 4, 6, 8 ];
var integers2 = [ 2, , , 8 ];
outputArray( "Array colors contains", colors );
outputArray( "Array integers1 contains", integers1 );
outputArray( "Array integers2 contains", integers2 );
}
66
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// output "header" followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray( header, theArray )
{
document.writeln( "<h2>" + header + "</h2>" );
document.writeln( "<table border = \"1\"" +
"width = \"100%\">" );
document.writeln( "<thead><th width = \"100\" " +
"align = \"left\">Subscript</th>" +
"<th align = \"left\">Value</th></thead><tbody>" );
InitArray2.html
for ( var i = 0; i < theArray.length; i++ )
document.writeln( "<tr><td>" + i + "</td><td>" +
theArray[ i ] + "</td></tr>" );
document.writeln( "</tbody></table>" );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
67
Program Output
68
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
SumArray.html
<!-- SumArray.html
-->
<!-- Summing Elements of an Array -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
for loop sums
<title>Sum the Elements ofThe
an Array</title>
the values contained in the 10element integer array called theArray.
<script type = "text/javascript">
<!-function start()
{
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var total1 = 0, total2 = 0;
for ( var i = 0; i < theArray.length;
i++ )
Variable element
total1 += theArray[ i ];
document.writeln( "Total
is assigned a subscript
in the range of 0 up to, but not including,
theArray.length.
using
subscripts: " + total1 );
for ( var element in theArray )
total2 += theArray[ element ];
document.writeln( "<br />Total using for/in: " +
total2 );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
69
Program Output
70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
RollDie.html
<!-- RollDie.html
-->
<!-- Roll a Six-Sided Die 6000 Times -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Roll a Six-SidedReferencing
Die 6000 Times</title>
Array frequency
replaces the
switch statement used in Chapter 10’s example.
"text/javascript">
<script type =
<!-var face, frequency = [ , 0, 0, 0, 0, 0, 0 ];
// summarize results
for ( var roll = 1; roll <= 6000; ++roll ) {
face = Math.floor( 1 + Math.random() * 6 );
++frequency[ face ];
}
document.writeln( "<table border = \"1\"" +
"width = \"100%\">" );
document.writeln( "<thead><th width = \"100\"" +
" align = \"left\">Face<th align = \"left\">" +
"Frequency</th></thead></tbody>" );
for ( face = 1; face < frequency.length; ++face )
document.writeln( "<tr><td>" + face + "</td><td>" +
frequency[ face ] + "</td></tr>" );
document.writeln( "</tbody></table>" );
// -->
</script>
71
36
37
38
39
40
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
RollDie.html
Program Output
72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- PassArray.html
<!-- Passing Arrays
PassArray.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Passing Arrays and Individual Array
Elements to Functions</title>
The first call to function outputArray displays the
of the Array a before it is modified.
<script type = "text/javascript">
contents
<!-function start()
{
var a = [ 1, 2, 3, 4, 5 ];
FunctionofmodifyArray
multiplies
each element
document.writeln( "<h2>Effects
passing entire
" +
"array call-by-reference</h2>" );
outputArray(
a[ "The
3 ] isvalues
output of
to show
its function
the Again,
original
arrayoutputArray
are: ", a ); is called to show
The value of
contents before it is modified.
modifyArray( a );
by 2.
that the contents of Array a have been modified.
the
multiplies
// arrayFunction
a passedmodifyElement
call-by-reference
contents of a[ 3 ] by 2.
outputArray(
"The values of the modified array are: ", a );
document.writeln( "<h2>Effects of passing array " +
"element call-by-value</h2>" +
"a[3] before modifyElement: " + a[ 3 ] );
modifyElement( a[ 3 ] );
73
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
document.writeln(
"<br />a[3] after modifyElement: " + a[ 3 ] );
PassArray.html
}
// outputs "header" followed by the contents of "theArray"
function outputArray( header, theArray )
{
document.writeln(
header + theArray.join( " " ) + "<br />" );
}
// function that modifies the elements
of join
an array
Method
takes as its argument a string
function modifyArray( theArray ) containing a separator that should be used to
{
separate the elements of the array in the string
for ( var j in theArray )
theArray[ j ] *= 2;
that is returned.
}
// function that attempts to modify the value passed
function modifyElement( e )
Multiply each element in theArray
{
e *= 2;
document.writeln( "<br />value in modifyElement: " + e );
}
// -->
</script>
by 2.
</head><body onload = "start()"></body>
</html>
74
Program Output
75
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- sort.html
<!-- Sorting an Array
Sort.html
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Sorting an ArrayMethod
with Array
Method
sort</title>
sort takes
as its
optional argument
the name of a
function that compares two arguments and returns a value
"text/javascript">
of –1, 0 or 1.
<script type =
<!-function start()
{
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
document.writeln( "<h1>Sorting an Array</h1>" );
outputArray( "Data items in original order: ", a );
a.sort( compareIntegers ); // sort the array
outputArray( "Data items in ascending order: ", a );
}
compareIntegers
calculates the
// outputs "header" followedFunction
by the contents
of "theArray"
function outputArray( header,
theArraybetween
)
difference
the integer values of its arguments.
{
document.writeln( "<p>" + header +
theArray.join( " " ) + "</p>" );
}
76
31
32
33
34
35
36
37
38
39
40
// comparison function for use with sort
function compareIntegers( value1, value2 )
{
return parseInt( value1 ) - parseInt( value2 );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
Sort.html
Program Output
77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- LinearSearch.html
<!-- Linear Search of an Array
LinearSearch.htm
-->
-->
Array a is initiated with 100 elements.
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Linear Search of an Array</title>
Array a is populated
<script type = "text/javascript">
<!-var a = new Array( 100 ); // create an Array
with the integers 0 to 198.
// fill Array with even integer values from 0 to 198
for ( var i = 0; i < a.length; ++i )
a[ i ] = 2 * i;
// function called when "Search" button is pressed
function buttonPressed()
{
var searchKey = searchForm.inputVal.value;
// Array a is passed to linearSearch even though it
// is a global variable. Normally an
array
Get
valuewill
of search key
// be passed to a method for searching.
the XHTML form.
var element = linearSearch( a, parseInt( searchKey ) );
from the input field in
if ( element != -1 )
Calling function linearSearch and
searchForm.result.value =
the" Array
a and the value of variable
"Found value in element
+ element;
searchKey as an integer.
else
searchForm.result.value = "Value not found";
}
passing it
78
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Search "theArray" for the specified "key" value
function linearSearch( theArray, key )
{
for ( var n = 0; n < theArray.length; ++n )
if ( theArray[ n ] == key )
return n;
return -1;
}
// -->
</script>
</head>
LinearSearch.htm
Function linearSearch compares each
each element with a search key.
Variable theArray gets the value
of Array a and variable key gets
the value of variable searchKey.
<body>
<form name = "searchForm" action = "">
<p>Enter integer search key<br />
<input name = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search"
onclick = "buttonPressed()" /><br /></p>
<p>Result<br />
<input name = "result" type = "text" size = "30" /></p>
</form>
</body>
</html>
79
Program Output
80
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- BinarySearch.html
<!-- binary search
BinarySearch.htm
-->
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Binary Search</title> Array a is
initiated with 15 elements.
<script type = "text/javascript">
<!-var a = new Array( 15 );
for ( var i = 0; i < a.length; ++i )
a[ i ] = 2 * i;
// function called when "Search" button is pressed
function buttonPressed()
{
var searchKey = searchForm.inputVal.value;
Function binarySearch receives two
searchForm.result.value =
"Portions of array searched\n";
arguments: the Array a and the search
key,
searchKey.
// Array a is passed to binarySearch
even though it
// is a global variable. This is done because
// normally an array is passed to a method
// for searching.
var element =
binarySearch( a, parseInt( searchKey ) );
81
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
if ( element != -1 )
searchForm.result.value +=
"\nFound value in element " + element;
else
searchForm.result.value += "\nValue not found";
BinarySearch.htm
}
// Binary search
function binarySearch( theArray, key )
{
var low = 0;
// low subscript
var high = theArray.length - 1; // high subscript
var middle;
// middle subscript
while ( low <= high ) {
middle = ( low + high ) / 2;
// The following line isIfused
to display
the key
matches the
the middle element of a
// part of theArray currently being manipulated
the subscript of the current element is
// during each iterationsubarray,
of the binary
// search loop.
returned.
If key
is less
than);the middle element, the high
buildOutput( theArray, low,
middle,
high
subscript is set to middle – 1.
if ( key == theArray[ middle ] ) // match
return middle;
else if ( key < theArray[
middle
] ) then the middle elements,
If key
is greater
high = middle - 1; // search low end of array
high subscript is set to middle +1.
else
low = middle + 1; // search high end of array
the
}
return -1;
// searchKey not found
}
82
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Build one row of output showing the current
// part of the array being processed.
function buildOutput( theArray, low, mid, high )
{
for ( var i = 0; i < theArray.length; i++ ) {
if ( i < low || i > high )
Function buildOutput
creates the
searchForm.result.value
+= "
";
// mark middle
element
output
displays
the in
results
of the search.
else if ( i == mid )
searchForm.result.value += a[ i ] +
( theArray[ i ] < 10 ? "* " : "* " );
else
searchForm.result.value += a[ i ] +
( theArray[ i ] < 10 ? "
" : " " );
}
BinarySearch.htm
markup that
searchForm.result.value += "\n";
}
// -->
</script>
</head>
<body>
<form name = "searchForm" action = "">
<p>Enter integer search key<br />
<input name = "inputVal" type = "text" />
<input name = "search" type = "button" value =
"Search" onclick = "buttonPressed()" /><br /></p>
<p>Result<br />
<textarea name = "result" rows = "7" cols = "60">
</textarea></p>
</form>
</body>
</html>
83
Program Output
84
Multiple-Subscripted Arrays
Co lum n 0
Ro w 0
Ro w 1
Ro w 2
Co lum n 1
Co lum n 2
Co lum n 3
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column sub sc rip t (o r index)
Ro w subsc rip t (or inde x)
Arra y na me
Double-subscripted array with three rows and four columns.
85
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Array array1
<!-- InitArray3.html
-->
<!-- Initializing Multidimensional
-->
twoArrays
sublists.
provides six initializers in
<html xmlns = "http://www.w3.org/1999/xhtml">
Array array2 provides
<head>
<title>Initializing Multidimensional
Arrays</title>
three sublists.
<script type = "text/javascript">
<!-function start()
{
var array1 = [ [ 1, 2, 3 ],
[ 4, 5, 6 ] ];
var array2 = [ [ 1, 2 ],
[ 3 ],
[ 4, 5, 6 ] ];
//
//
//
//
//
InitArray3.html
six initializers in
first row
second row
first row
second row
third row
Function outputArray displays each array’s
in aby
Web
page.array1 );
"Valueselements
in array1
row",
outputArray(
outputArray( "Values in array2 by row", array2 );
}
function outputArray( header, theArray )
{
document.writeln( "<h2>" + header + "</h2><tt>" );
86
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
for ( var i in theArray ) {
InitArray3.html
for ( var j in theArray[ i ] )
document.write( theArray[ i ][ j ] + " " );
document.writeln( "<br />" );
}
document.writeln( "</tt>" );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
Referencing the multidimensional
array theArray.
Program Output
87
End of Lecture
88