Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 JavaScript: Control Structures II. 2 whileCounter.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Similar presentations


Presentation on theme: "1 JavaScript: Control Structures II. 2 whileCounter.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">"— Presentation transcript:

1 1 JavaScript: Control Structures II

2 2 whileCounter.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Counter-Controlled Repetition 11 12 13 <!-- 14 var counter = 1; // initialization 15 16 while ( counter <= 7 ) { // repetition condition 17 document.writeln( "<p style = \"font-size: " + 18 counter + "ex\">XHTML font size " + counter + 19 "ex " ); 20 ++counter; // increment 21 } 22 // --> 23 24 25 26 The while loop will continue until the value of counter is greater than 7. Increment the counter.

3 3 Program Output

4 4 ForCounter.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Counter-Controlled Repetition 11 12 13 <!-- 14 // Initialization, repetition condition and 15 // incrementing are all included in the for 16 // structure header. 17 for ( var counter = 1; counter <= 7; ++counter ) 18 document.writeln( "<p style = \"font-size: " + 19 counter + "ex\">XHTML font size " + counter + 20 "ex " ); 21 // --> 22 23 24 25 InitializationRepetition conditionIncrementing

5 5 Program Output

6 6 For Repetition Structure for (var counter = 1 ; counter <= 7 ; ++counter ) Initial value of control variableIncrement of control variable Control variable nameFinal value of control variable for which the condition is true for keyword Loop-continuation condition Components of a typical for structure header.

7 7 Examples Using the for Structure counter <= 7 document.writeln( "<p style=\"font-size: " + counter + "ex\">XHTML font size "+ counter + "ex " ); true false var counter = 1 ++counter Establish initial value of control variable. Determine if final value of control variable has been reached. Body of loop (this may be many statements) Increment the control variable. Flowcharting a typical for repetition structure.

8 8 Sum.html Sum.html Program Output 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Sum the Even Integers from 2 to 100 11 12 13 <!-- 14 var sum = 0; 15 16 for ( var number = 2; number <= 100; number += 2 ) 17 sum += number; 18 19 document.writeln( "The sum of the even integers " + 20 "from 2 to 100 is " + sum ); 21 // --> 22 23 24 25 The for loop will continue until the value of number is greater than 100. Initialization.Repetition condition.Incrementing.

9 9 Interest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Calculating Compound Interest 11 12 13 <!-- 14 var amount, principal = 1000.0, rate =.05; 15 16 document.writeln( 17 " " ); 18 document.writeln( 19 " Calculating Compound Interest " ); 20 document.writeln( 21 " Year " ); 22 document.writeln( 23 " Amount on deposit " ); 24 document.writeln( " " ); 25 26 for ( var year = 1; year <= 10; ++year ) { 27 amount = principal * Math.pow( 1.0 + rate, year ); 28 document.writeln( " " + year + 29 " " + Math.round( amount * 100 ) / 100 + 30 " " ); 31 } 32 33 document.writeln( " " ); 34 // --> 35 Opening table element.Each iteration of the for loop creates a table row listing the year of the loan and the amount.

10 10 Interest.html Interest.html Program Output 36 37 38

11 11 SwitchTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Switching between XHTML List Formats 11 12 13 <!-- 14 var choice, // user’s choice 15 startTag, // starting list item tag 16 endTag, // ending list item tag 17 validInput = true, // indicates if input is valid 18 listType; // list type as a string 19 20 choice = window.prompt( "Select a list style:\n" + 21 "1 (bullet), 2 (numbered), 3 (lettered)", "1" ); 22 23 switch ( choice ) { 24 case "1": 25 startTag = " "; 26 endTag = " "; 27 listType = " Bullet List "; 28 break; 29 case "2": 30 startTag = " "; 31 endTag = " "; 32 listType = " Ordered List: Numbered "; 33 break; The value of choice is evaluated against each of the values of the case labels. Variable choice is given the value input by the user in the prompt dialog. The break statement causes program control to proceed with the first statement after the switch structure.

12 12 SwitchTest.html 34 case "3": 35 startTag = " "; 36 endTag = " "; 37 listType = " Ordered List: Lettered "; 38 break; 39 default: 40 validInput = false; 41 } 42 43 if ( validInput == true ) { 44 document.writeln( listType + startTag ); 45 46 for ( var i = 1; i <= 3; ++i ) 47 document.writeln( " List item " + i + " " ); 48 49 document.writeln( endTag ); 50 } 51 else 52 document.writeln( "Invalid choice: " + choice ); 53 // --> 54 55 56 57 58 Click Refresh (or Reload) to run the script again 59 60 If none of the case s match, variable validInput is set to false. If the user input a valid value, the list is created. Otherwise, the message “Invalid choice” is displayed in the browser.

13 13 Program Output

14 14 Program Output

15 15 switch Multiple-Selection Structure...... switch multiple-selection structure.

16 16 DoWhileTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Using the do/while Repetition Structure 11 12 13 <!-- 14 var counter = 1; 15 16 do { 17 document.writeln( " This is " + 18 "an h" + counter + " level head" + "</h" + 19 counter + ">" ); 20 21 ++counter; 22 } while ( counter <= 6 ); 23 // --> 24 25 26 27 Each iteration of the do / while loop writes a line of text with a header element to the XHTML document. The loop stops when the value of counter is greater than 6.

17 17 Program Output

18 18 do/while Repetition Structure condition true action(s) false Flowcharting the do/while repetition structure.

19 19 BreakTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 11 Using the break Statement in a for Structure 12 13 14 15 <!-- 16 for ( var count = 1; count <= 10; ++count ) { 17 if ( count == 5 ) 18 break; // break loop only if count == 5 19 20 document.writeln( "Count is: " + count + " " ); 21 } 22 23 document.writeln( 24 "Broke out of loop at count = " + count ); 25 // --> 26 27 28 29 When the value of variable count equals 5, the break statement causes program control to proceed to the first line outside the for loop.

20 20 Program Output

21 21 ContinueTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 11 Using the continue Statement in a for Structure 12 13 14 15 <!-- 16 for ( var count = 1; count <= 10; ++count ) { 17 if ( count == 5 ) 18 continue; // skip remaining code in loop 19 // only if count == 5 20 21 document.writeln( "Count is: " + count + " " ); 22 } 23 24 document.writeln( "Used continue to skip printing 5" ); 25 // --> 26 27 28 29 When the value of variable count equals 5, the continue statement causes program control to proceed to the next iteration of the for loop.

22 22 Program Output

23 23 BreakLabelTest.htm 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Using the break Statement with a Label 11 12 13 <!-- 14 stop: { // labeled compound statement 15 for ( var row = 1; row <= 10; ++row ) { 16 for ( var column = 1; column <= 5 ; ++column ) { 17 18 if ( row == 5 ) 19 break stop; // jump to end of stop block 20 21 document.write( "* " ); 22 } 23 24 document.writeln( " " ); 25 } 26 27 // the following line is skipped 28 document.writeln( "This line should not print" ); 29 } 30 When the break statement is encountered, program control proceeds to the first line outside the stop block and not just the for loop where the statement is found. stop is the label for the break statement.

24 24 B reakLabelTest.htm B reakLabelTest.htm Program Output 31 document.writeln( "End of script" ); 32 // --> 33 34 35 36

25 25 ContinueLabelTest.htm 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Using the continue Statement with a Label 11 12 13 <!-- 14 nextRow: // target label of continue statement 15 for ( var row = 1; row <= 5; ++row ) { 16 document.writeln( " " ); 17 18 for ( var column = 1; column <= 10; ++column ) { 19 20 if ( column > row ) 21 continue nextRow; // next iteration of 22 // labeled loop 23 24 document.write( "* " ); 25 } 26 } 27 // --> 28 29 30 31 nextRow is the label for the continue statement.If the value of variable column is greater than the value of variable row, the continue statement causes the next interation of the loop. If the continue statement is performed, method write does not print the string “* “ in the XHTML document.

26 26 Program Output

27 27 LogicalOperators.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Demonstrating the Logical Operators 11 12 13 <!-- 14 document.writeln( 15 " " ); 16 17 document.writeln( 18 " Demonstrating Logical " + 19 "Operators</caption" ); 20 21 document.writeln( 22 " Logical AND (&&) " + 23 " false && false: " + ( false && false ) + 24 " false && true: " + ( false && true ) + 25 " true && false: " + ( true && false ) + 26 " true && true: " + ( true && true ) + 27 " " ); 28 29 document.writeln( 30 " Logical OR (||) " + 31 " false || false: " + ( false || false ) + 32 " false || true: " + ( false || true ) + 33 " true || false: " + ( true || false ) + 34 " true || true: " + ( true || true ) + 35 " " ); Each expression will evaluate to true or false using the rules of logical AND. Each expression will evaluate to true or false using the rules of logical OR.

28 28 LogicalOperators.html LogicalOperators.html Program Output 36 37 document.writeln( 38 " Logical NOT (!) " + 39 " !false: " + ( !false ) + 40 " !true: " + ( !true ) + " " ); 41 42 document.writeln( " " ); 43 // --> 44 45 46 47 These expressions demonstrate the use of logical NOT.

29 29 Summary of Structured Programming JavaScript’s single-entry/single-exit sequence, selection and repetition structures.

30 30 Summary of Structured Programming Unstructured flowchart.

31 31 JavaScript: Functions

32 32 Program Modules in JavaScript main worker1worker2worker3 worker4worker5 Hierarchical boss-function/worker-function relationship.

33 33 SquareInt.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 A Programmer-Defined square Function 11 12 13 <!-- 14 document.writeln( 15 " Square the numbers from 1 to 10 " ); 16 17 // square the numbers from 1 to 10 18 for ( var x = 1; x <= 10; ++x ) 19 document.writeln( "The square of " + x + " is " + 20 square( x ) + " " ); 21 22 // The following square function's body is executed 23 // only when the function is explicitly called. 24 25 // square function definition 26 function square( y ) 27 { 28 return y * y; 29 } 30 // --> 31 32 33 34 Calling function square and passing it the value of x.Variable y gets the value of variable x. The return statement passes the value of y * y back to the calling function.

34 34 Program Output

35 35 Maximum.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Finding the Maximum of Three Values 11 12 13 <!-- 14 var input1 = 15 window.prompt( "Enter first number", "0" ); 16 var input2 = 17 window.prompt( "Enter second number", "0" ); 18 var input3 = 19 window.prompt( "Enter third number", "0" ); 20 21 var value1 = parseFloat( input1 ); 22 var value2 = parseFloat( input2 ); 23 var value3 = parseFloat( input3 ); 24 25 var maxValue = maximum( value1, value2, value3 ); 26 27 document.writeln( "First number: " + value1 + 28 " Second number: " + value2 + 29 " Third number: " + value3 + 30 " Maximum is: " + maxValue ); 31 32 // maximum method definition (called from line 25) 33 function maximum( x, y, z ) 34 { 35 return Math.max( x, Math.max( y, z ) ); Prompt for the user to input three integers. Call function maximum and pass it the value of variables value1, value2 and value3. Variables x, y and z get the value of variables value1, value2 and value3, respectively. Method max returns the larger of the two integers passed to it.

36 36 Maximum.html Maximum.html Program Output 36 } 37 // --> 38 39 40 41 42 Click Refresh (or Reload) to run the script again 43 44

37 37 Program Output

38 38 RandomInt.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Shifted and Scaled Random Integers 11 12 13 <!-- 14 var value; 15 16 document.writeln( 17 " " ); 18 document.writeln( 19 " Random Numbers " ); 20 21 for ( var i = 1; i <= 20; i++ ) { 22 value = Math.floor( 1 + Math.random() * 6 ); 23 document.writeln( " " + value + " " ); 24 25 // write end and start tags when 26 // i is a multiple of 5 and not 20 27 if ( i % 5 == 0 && i != 20 ) 28 document.writeln( " " ); 29 } 30 31 document.writeln( " " ); 32 // --> 33 34 35 The for loop creates 4 rows with 5 cells of a table.Each cell is populated with a random number generated by method random. Method floor rounds the number generated by method random down.

39 39 RandomInt.html RandomInt.html Program Output 36 37 Click Refresh (or Reload) to run the script again 38 39

40 40 RollD.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Roll a Six-Sided Die 6000 Times 11 12 13 <!-- 14 var frequency1 = 0, frequency2 = 0, 15 frequency3 = 0, frequency4 = 0, 16 frequency5 = 0, frequency6 = 0, face; 17 18 // summarize results 19 for ( var roll = 1; roll <= 6000; ++roll ) { 20 face = Math.floor( 1 + Math.random() * 6 ); 21 22 switch ( face ) { 23 case 1: 24 ++frequency1; 25 break; 26 case 2: 27 ++frequency2; 28 break; 29 case 3: 30 ++frequency3; 31 break; 32 case 4: 33 ++frequency4; 34 break; 35 case 5: This expression uses method random to generate a random number between 1 and 6. When the controlling expression, face, matches a case label, the respective frequency variable is incremented.

41 41 RollD.html 36 ++frequency5; 37 break; 38 case 6: 39 ++frequency6; 40 break; 41 } 42 } 43 44 document.writeln( "<table border = \"1\"" + 45 "width = \"50%\">" ); 46 document.writeln( " Face " + 47 " Frequency " ); 48 document.writeln( " 1 " + 49 frequency1 + " " ); 50 document.writeln( " 2 " + frequency2 + 51 " " ); 52 document.writeln( " 3 " + frequency3 + 53 " " ); 54 document.writeln( " 4 " + frequency4 + 55 " " ); 56 document.writeln( " 5 " + frequency5 + 57 " " ); 58 document.writeln( " 6 " + frequency6 + 59 " " ); 60 // --> 61 62 63 64 65 Click Refresh (or Reload) to run the script again 66 67 The results of the dice being rolled 600 times are displayed in a table.

42 42 Program Output

43 43 Craps.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 6 7 8 9 10 Program that Simulates the Game of Craps 11 12 13 <!-- 14 // variables used to test the state of the game 15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 16 17 // other variables used in program 18 var firstRoll = true, // true if first roll 19 sumOfDice = 0, // sum of the dice 20 myPoint = 0, // point if no win/loss on first roll 21 gameStatus = CONTINUE_ROLLING; // game not over yet 22 23 // process one roll of the dice 24 function play() 25 { 26 if ( firstRoll ) { // first roll of the dice 27 sumOfDice = rollDice(); 28 29 switch ( sumOfDice ) { 30 case 7: case 11: // win on first roll 31 gameStatus = WON; 32 // clear point field 33 document.craps.point.value = ""; 34 break; 35 case 2: case 3: case 12: // lose on first roll If the value of firstRoll is true, then function rollDice is called. If function rollDice returns a value of 7 or 11, theplayer wins and the break statement causes program control proceeds to the first line after the switch structure.

44 44 Craps.html 36 gameStatus = LOST; 37 // clear point field 38 document.craps.point.value = ""; 39 break; 40 default: // remember point 41 gameStatus = CONTINUE_ROLLING; 42 myPoint = sumOfDice; 43 document.craps.point.value = myPoint; 44 firstRoll = false; 45 } 46 } 47 else { 48 sumOfDice = rollDice(); 49 50 if ( sumOfDice == myPoint ) // win by making point 51 gameStatus = WON; 52 else 53 if ( sumOfDice == 7 ) // lose by rolling 7 54 gameStatus = LOST; 55 } 56 57 if ( gameStatus == CONTINUE_ROLLING ) 58 window.status = "Roll again"; 59 else { 60 if ( gameStatus == WON ) 61 window.status = "Player wins. " + 62 "Click Roll Dice to play again."; 63 else 64 window.status = "Player loses. " + 65 "Click Roll Dice to play again."; 66 67 firstRoll = true; 68 } 69 } 70 If function rollDice retursn a 2, 3 or 12, the player loses and the break statement causes control to proceed to first line after the switch structure. If the value returned by function rollDice equals the value of variable myPoint, the player wins because the point has been reached. If the values returned by function rollDice equals 7, the player loses. window method status displays a message in the status bar of the browser.

45 45 Craps.html 71 // roll the dice 72 function rollDice() 73 { 74 var die1, die2, workSum; 75 76 die1 = Math.floor( 1 + Math.random() * 6 ); 77 die2 = Math.floor( 1 + Math.random() * 6 ); 78 workSum = die1 + die2; 79 80 document.craps.firstDie.value = die1; 81 document.craps.secondDie.value = die2; 82 document.craps.sum.value = workSum; 83 84 return workSum; 85 } 86 // --> 87 88 89 90 91 92 93 Craps 94 Die 1 95 96 97 Die 2 98 99 100 Sum 101 102 103 Point 104 105 Function rollDice is called to simulate the rolling of two dice on the craps table. Methods random and floor are used to generate the values for the two dice. Referencing the names of form elements in the XHTML document, the vlaues of the dice are placed in their respective form fields.

46 46 Craps.html Craps.html Program Output 106 <input type = "button" value = "Roll Dice" 107 onclick = "play()" /> 108 109 110 111

47 47 Program Output

48 48 Program Output

49 49 Scoping.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 A Scoping Example 11 12 13 <!-- 14 var x = 1; // global variable 15 16 function start() 17 { 18 var x = 5; // variable local to function start 19 20 document.writeln( "local x in start is " + x ); 21 22 functionA(); // functionA has local x 23 functionB(); // functionB uses global variable x 24 functionA(); // functionA reinitializes local x 25 functionB(); // global variable x retains its value 26 27 document.writeln( 28 " local x in start is " + x + " " ); 29 } 30 31 function functionA() 32 { 33 var x = 25; // initialized each time 34 // functionA is called To begin the program, variable x is initialized to 1.Function start changes the value of x to 5.Function functionA changes the value of x to 25.

50 50 Scoping.html 35 36 document.writeln( " local x in functionA is " + 37 x + " after entering functionA" ); 38 ++x; 39 document.writeln( " local x in functionA is " + 40 x + " before exiting functionA" + " " ); 41 } 42 43 function functionB() 44 { 45 document.writeln( " global variable x is " + x + 46 " on entering functionB" ); 47 x *= 10; 48 document.writeln( " global variable x is " + 49 x + " on exiting functionB" + " " ); 50 } 51 // --> 52 53 54 55 56 The value of x is incremented. Function functionB multiplies the value of x by 10.

51 51 Program Output

52 52 JavaScript Global Functions

53 53 JavaScript Global Functions

54 54 Recursion 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (a) Procession of recursive calls.(b) Values returned from each recursive call. 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 2! = 2 * 1 = 2 is returned 3! = 3 * 2 = 6 is returned 1 returned Recursive evaluation of 5!. Final value = 120

55 55 FactorialTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Recursive Factorial Function 10 11 12 document.writeln( " Factorials of 1 to 10 " ); 13 document.writeln( 14 " " ); 15 16 for ( var i = 0; i <= 10; i++ ) 17 document.writeln( " " + i + "! " + 18 factorial( i ) + " " ); 19 20 document.writeln( " " ); 21 22 // Recursive definition of function factorial 23 function factorial( number ) 24 { 25 if ( number <= 1 ) // base case 26 return 1; 27 else 28 return number * factorial( number - 1 ); 29 } 30 31 32 Calling function factorial and passing it the value of i. Variable number gets the value of variable i.Call to function factorial and passing it 1 less than the current value of number.

56 56 Program Output

57 57 FibonacciTest.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 6 7 8 9 Recursive Fibonacci Function 10 11 12 13 // Event handler for button XHTML component in myForm 14 function getFibonacciValue() 15 { 16 var value = parseInt( 17 document.myForm.number.value ); 18 window.status = 19 "Calculating Fibonacci number for " + value; 20 document.myForm.result.value = fibonacci( value ); 21 window.status = "Done calculating Fibonacci number"; 22 } 23 24 // Recursive definition of function fibonacci 25 function fibonacci( n ) 26 { 27 if ( n == 0 || n == 1 ) // base case 28 return n; 29 else 30 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 31 } 32 33 34 Convert from a string to an integer the value the user typed into the number text field. Display the number the user entered in the status bar. The status bar displays a message that the call to function fibonacci is complete. Test for base case ( n equal to 1 or 0 ). Two recursive calls are made if n is greater than 1.

58 58 FibonacciTest.html FibonacciTest.html Program Output 35 36 37 38 Enter an integer 39 40 <input type = "button" value = "Calculate" 41 onclick = "getFibonacciValue()" 42 Fibonacci value 43 44 45 46

59 59 Program Output

60 60 Example Using Recursion: Fibonacci Series Set of recursive calls to function fibonacci.

61 61 JavaScript: Arrays

62 62 Arrays c[ 6 ] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array (Note that all elements of this array have the same name, c ) c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 11 ] c[ 10 ] c[ 9 ] c[ 8 ] c[ 7 ] c[ 5 ] c[ 4 ] Position number (index or subscript) of the element within array c A 12-element array.

63 63 InitArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Initializing an Array 11 12 13 <!-- 14 // this function is called when the element's 15 // onload event occurs 16 function initializeArrays() 17 { 18 var n1 = new Array( 5 ); // allocate 5-element Array 19 var n2 = new Array(); // allocate empty Array 20 21 // assign values to each element of Array n1 22 for ( var i = 0; i < n1.length; ++i ) 23 n1[ i ] = i; 24 25 // create and initialize five-elements in Array n2 26 for ( i = 0; i < 5; ++i ) 27 n2[ i ] = i; 28 29 outputArray( "Array n1 contains", n1 ); 30 outputArray( "Array n2 contains", n2 ); 31 } 32 Array n1 has five elements.The for loop initializes the elements in n1 to their subscript numbers (0 to 4). Array n2 is an empty array.The for loop adds five elements to Array n2 and initialize each element to its subscript number (0 to 4). Each function displays the contents of its respective Array in an XHTML table.

64 64 InitArray.html 33 // output "header" followed by a two-column table 34 // containing subscripts and elements of "theArray" 35 function outputArray( header, theArray ) 36 { 37 document.writeln( " " + header + " " ); 38 document.writeln( "<table border = \"1\" width =" + 39 "\"100%\">" ); 40 41 document.writeln( " <th width = \"100\"" + 42 "align = \"left\">Subscript " + 43 " Value " ); 44 45 for ( var i = 0; i < theArray.length; i++ ) 46 document.writeln( " " + i + " " + 47 theArray[ i ] + " " ); 48 49 document.writeln( " " ); 50 } 51 // --> 52 53 54 55 The first time function ouputArray is called, variable header gets the value of “Array n1 contains ” and variable theArray gets the value of n1. The second time function ouputArray is called, variable header gets the value of “Array n2 contains ” and variable theArray gets the value of n2.

65 65 Program Output

66 66 InitArray2.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Initializing an Array with a Declaration 11 12 13 <!-- 14 function start() 15 { 16 // Initializer list specifies number of elements and 17 // value for each element. 18 var colors = new Array( "cyan", "magenta", 19 "yellow", "black" ); 20 var integers1 = [ 2, 4, 6, 8 ]; 21 var integers2 = [ 2,,, 8 ]; 22 23 outputArray( "Array colors contains", colors ); 24 outputArray( "Array integers1 contains", integers1 ); 25 outputArray( "Array integers2 contains", integers2 ); 26 } 27 Array integers1 is initialized using an initializer list.Two values are not supplied for integer2, which will be displayed as undefined.

67 67 InitArray2.html 28 // output "header" followed by a two-column table 29 // containing subscripts and elements of "theArray" 30 function outputArray( header, theArray ) 31 { 32 document.writeln( " " + header + " " ); 33 document.writeln( "<table border = \"1\"" + 34 "width = \"100%\">" ); 35 document.writeln( " <th width = \"100\" " + 36 "align = \"left\">Subscript " + 37 " Value " ); 38 39 for ( var i = 0; i < theArray.length; i++ ) 40 document.writeln( " " + i + " " + 41 theArray[ i ] + " " ); 42 43 document.writeln( " " ); 44 } 45 // --> 46 47 48 49

68 68 Program Output

69 69 SumArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Sum the Elements of an Array 11 12 13 <!-- 14 function start() 15 { 16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; 17 var total1 = 0, total2 = 0; 18 19 for ( var i = 0; i < theArray.length; i++ ) 20 total1 += theArray[ i ]; 21 22 document.writeln( "Total using subscripts: " + total1 ); 23 24 for ( var element in theArray ) 25 total2 += theArray[ element ]; 26 27 document.writeln( " Total using for/in: " + 28 total2 ); 29 } 30 // --> 31 32 33 34 The for loop sums the values contained in the 10- element integer array called theArray. Variable element is assigned a subscript in the range of 0 up to, but not including, theArray.length.

70 70 Program Output

71 71 RollDie.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Roll a Six-Sided Die 6000 Times 11 12 13 <!-- 14 var face, frequency = [, 0, 0, 0, 0, 0, 0 ]; 15 16 // summarize results 17 for ( var roll = 1; roll <= 6000; ++roll ) { 18 face = Math.floor( 1 + Math.random() * 6 ); 19 ++frequency[ face ]; 20 } 21 22 document.writeln( "<table border = \"1\"" + 23 "width = \"100%\">" ); 24 document.writeln( " <th width = \"100\"" + 25 " align = \"left\">Face " + 26 "Frequency " ); 27 28 for ( face = 1; face < frequency.length; ++face ) 29 document.writeln( " " + face + " " + 30 frequency[ face ] + " " ); 31 32 document.writeln( " " ); 33 // --> 34 35 Referencing Array frequency replaces the switch statement used in Chapter 10’s example.

72 72 RollDie.html RollDie.html Program Output 36 37 38 Click Refresh (or Reload) to run the script again 39 40

73 73 PassArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Passing Arrays and Individual Array 11 Elements to Functions 12 13 14 <!-- 15 function start() 16 { 17 var a = [ 1, 2, 3, 4, 5 ]; 18 19 document.writeln( " Effects of passing entire " + 20 "array call-by-reference " ); 21 outputArray( 22 "The values of the original array are: ", a ); 23 24 modifyArray( a ); // array a passed call-by-reference 25 26 outputArray( 27 "The values of the modified array are: ", a ); 28 29 document.writeln( " Effects of passing array " + 30 "element call-by-value " + 31 "a[3] before modifyElement: " + a[ 3 ] ); 32 33 modifyElement( a[ 3 ] ); 34 The first call to function outputArray displays the contents of the Array a before it is modified. Function modifyArray multiplies each element by 2.Again, function outputArray is called to show that the contents of Array a have been modified. The value of a[ 3 ] is output to show its contents before it is modified. Function modifyElement multiplies the contents of a[ 3 ] by 2.

74 74 PassArray.html 35 document.writeln( 36 " a[3] after modifyElement: " + a[ 3 ] ); 37 } 38 39 // outputs "header" followed by the contents of "theArray" 40 function outputArray( header, theArray ) 41 { 42 document.writeln( 43 header + theArray.join( " " ) + " " ); 44 } 45 46 // function that modifies the elements of an array 47 function modifyArray( theArray ) 48 { 49 for ( var j in theArray ) 50 theArray[ j ] *= 2; 51 } 52 53 // function that attempts to modify the value passed 54 function modifyElement( e ) 55 { 56 e *= 2; 57 document.writeln( " value in modifyElement: " + e ); 58 } 59 // --> 60 61 62 63 Method join takes as its argument a string containing a separator that should be used to separate the elements of the array in the string that is returned. Multiply each element in theArray by 2.

75 75 Program Output

76 76 Sort.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Sorting an Array with Array Method sort 11 12 13 <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 17 18 document.writeln( " Sorting an Array " ); 19 outputArray( "Data items in original order: ", a ); 20 a.sort( compareIntegers ); // sort the array 21 outputArray( "Data items in ascending order: ", a ); 22 } 23 24 // outputs "header" followed by the contents of "theArray" 25 function outputArray( header, theArray ) 26 { 27 document.writeln( " " + header + 28 theArray.join( " " ) + " " ); 29 } 30 Method sort takes as its optional argument the name of a function that compares two arguments and returns a value of –1, 0 or 1. Function compareIntegers calculates the difference between the integer values of its arguments.

77 77 Sort.html Sort.html Program Output 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // --> 37 38 39 40

78 78 LinearSearch.htm 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Linear Search of an Array 11 12 13 <!-- 14 var a = new Array( 100 ); // create an Array 15 16 // fill Array with even integer values from 0 to 198 17 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; 19 20 // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; 24 25 // Array a is passed to linearSearch even though it 26 // is a global variable. Normally an array will 27 // be passed to a method for searching. 28 var element = linearSearch( a, parseInt( searchKey ) ); 29 30 if ( element != -1 ) 31 searchForm.result.value = 32 "Found value in element " + element; 33 else 34 searchForm.result.value = "Value not found"; 35 } Array a is initiated with 100 elements. Array a is populated with the integers 0 to 198. Get value of search key from the input field in the XHTML form. Calling function linearSearch and passing it the Array a and the value of variable searchKey as an integer.

79 79 LinearSearch.htm 36 37 // Search "theArray" for the specified "key" value 38 function linearSearch( theArray, key ) 39 { 40 for ( var n = 0; n < theArray.length; ++n ) 41 if ( theArray[ n ] == key ) 42 return n; 43 44 return -1; 45 } 46 // --> 47 48 49 50 51 52 53 Enter integer search key 54 55 <input name = "search" type = "button" value = "Search" 56 onclick = "buttonPressed()" /> 57 58 Result 59 60 61 62 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.

80 80 Program Output

81 81 BinarySearch.htm 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 6 7 8 9 10 Binary Search 11 12 13 <!-- 14 var a = new Array( 15 ); 15 16 for ( var i = 0; i < a.length; ++i ) 17 a[ i ] = 2 * i; 18 19 // function called when "Search" button is pressed 20 function buttonPressed() 21 { 22 var searchKey = searchForm.inputVal.value; 23 24 searchForm.result.value = 25 "Portions of array searched\n"; 26 27 // Array a is passed to binarySearch even though it 28 // is a global variable. This is done because 29 // normally an array is passed to a method 30 // for searching. 31 var element = 32 binarySearch( a, parseInt( searchKey ) ); 33 Array a is initiated with 15 elements.Function binarySearch receives two arguments: the Array a and the search key, searchKey.

82 82 BinarySearch.htm 34 if ( element != -1 ) 35 searchForm.result.value += 36 "\nFound value in element " + element; 37 else 38 searchForm.result.value += "\nValue not found"; 39 } 40 41 // Binary search 42 function binarySearch( theArray, key ) 43 { 44 var low = 0; // low subscript 45 var high = theArray.length - 1; // high subscript 46 var middle; // middle subscript 47 48 while ( low <= high ) { 49 middle = ( low + high ) / 2; 50 51 // The following line is used to display the 52 // part of theArray currently being manipulated 53 // during each iteration of the binary 54 // search loop. 55 buildOutput( theArray, low, middle, high ); 56 57 if ( key == theArray[ middle ] ) // match 58 return middle; 59 else if ( key < theArray[ middle ] ) 60 high = middle - 1; // search low end of array 61 else 62 low = middle + 1; // search high end of array 63 } 64 65 return -1; // searchKey not found 66 } 67 If the key matches the middle element of a subarray, the subscript of the current element is returned. If key is less than the middle element, the high subscript is set to middle – 1. If key is greater then the middle elements, the high subscript is set to middle +1.

83 83 BinarySearch.htm 68 // Build one row of output showing the current 69 // part of the array being processed. 70 function buildOutput( theArray, low, mid, high ) 71 { 72 for ( var i = 0; i < theArray.length; i++ ) { 73 if ( i high ) 74 searchForm.result.value += " "; 75 // mark middle element in output 76 else if ( i == mid ) 77 searchForm.result.value += a[ i ] + 78 ( theArray[ i ] < 10 ? "* " : "* " ); 79 else 80 searchForm.result.value += a[ i ] + 81 ( theArray[ i ] < 10 ? " " : " " ); 82 } 83 84 searchForm.result.value += "\n"; 85 } 86 // --> 87 88 89 90 91 92 Enter integer search key 93 94 <input name = "search" type = "button" value = 95 "Search" onclick = "buttonPressed()" /> 96 Result 97 98 99 100 101 Function buildOutput creates the markup that displays the results of the search.

84 84 Program Output

85 85 Multiple-Subscripted Arrays Double-subscripted array with three rows and four columns.

86 86 InitArray3.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Initializing Multidimensional Arrays 11 12 13 <!-- 14 function start() 15 { 16 var array1 = [ [ 1, 2, 3 ], // first row 17 [ 4, 5, 6 ] ]; // second row 18 var array2 = [ [ 1, 2 ], // first row 19 [ 3 ], // second row 20 [ 4, 5, 6 ] ]; // third row 21 22 outputArray( "Values in array1 by row", array1 ); 23 outputArray( "Values in array2 by row", array2 ); 24 } 25 26 function outputArray( header, theArray ) 27 { 28 document.writeln( " " + header + " " ); 29 Array array1 provides six initializers in two sublists. Array array2 provides six initializers in three sublists. Function outputArray displays each array’s elements in a Web page.

87 87 InitArray3.html InitArray3.html Program Output 30 for ( var i in theArray ) { 31 32 for ( var j in theArray[ i ] ) 33 document.write( theArray[ i ][ j ] + " " ); 34 35 document.writeln( " " ); 36 } 37 38 document.writeln( " " ); 39 } 40 // --> 41 42 43 44 Referencing the multidimensional array theArray.

88 88 End of Lecture


Download ppt "1 JavaScript: Control Structures II. 2 whileCounter.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">"

Similar presentations


Ads by Google