Chapter 11 Java ScriptJscript Functions Outline 11 1

  • Slides: 57
Download presentation
Chapter 11 – Java. Script/Jscript: Functions Outline 11. 1 11. 2 11. 3 11.

Chapter 11 – Java. Script/Jscript: Functions Outline 11. 1 11. 2 11. 3 11. 4 11. 5 11. 6 11. 7 11. 8 11. 9 11. 10 11. 11 11. 12 Introduction Program Modules in Java. Script Programmer-Defined Functions Function Definitions Random Number Generation Example: A Game of Chance Duration of Identifiers Scope Rules Recursion Example of Recursion: The Fibonacci Series Recursion vs. Iteration Java. Script Global Functions 2000 Deitel & Associates, Inc. All rights reserved.

11. 1 Introduction • Programs that solve real-world programs – More complex than programs

11. 1 Introduction • Programs that solve real-world programs – More complex than programs from previous chapters • Best way to develop & maintain large program: – Construct from small, simple pieces called modules – Technique called divide and conquer 2000 Deitel & Associates, Inc. All rights reserved.

11. 2 Program Modules in Java. Script • functions – Java. Script modules •

11. 2 Program Modules in Java. Script • functions – Java. Script modules • Java. Script programs written by combining – Functions programmer writes – “prepackaged” functions and objects in Java. Script • These functions often called methods • Implies function belongs to particular object • Java. Script provides several rich objects for performing – – Common mathematical operations String manipulation Date and time manipulation Manipulations of arrays 2000 Deitel & Associates, Inc. All rights reserved.

11. 2 Program Modules in Java. Script (II) • Programmer-defined functions – Written by

11. 2 Program Modules in Java. Script (II) • Programmer-defined functions – Written by programmer to define specific tasks – Statements defining functions written once – Statements are hidden from other functions • Function is invoked by a function call – Specifies function name – Provides information (or arguments) function needs for execution • Function call syntax: function. Name( argument ); 2000 Deitel & Associates, Inc. All rights reserved.

11. 3 Programmer-Defined Functions • Functions allow program modularization • Variables declared in function

11. 3 Programmer-Defined Functions • Functions allow program modularization • Variables declared in function are local variables – Only known inside function in which defined • Most functions have list of parameters – Means for communicating info between functions & function calls – Local variables – When function called, arguments assigned to parameters in function definition 2000 Deitel & Associates, Inc. All rights reserved.

11. 3 Programmer-Defined Functions (II) • Motives for modularizing a program with functions 1.

11. 3 Programmer-Defined Functions (II) • Motives for modularizing a program with functions 1. Makes program development more manageable 2. Allows software reusability • Programs can be created from standard functions instead of being built from customized code Example: parse. Int(), parse. Float • Functions should be limited to performing a single, well-defined task 3. Avoid repeating code in program • Do not re-invent the wheel • Save time 2000 Deitel & Associates, Inc. All rights reserved.

11. 3 Programmer-Defined Functions (III) • Naming functions – Choose concise names which describe

11. 3 Programmer-Defined Functions (III) • Naming functions – Choose concise names which describe what function does – If not possible to describe briefly, your function is too complex 2000 Deitel & Associates, Inc. All rights reserved.

11. 4 Function Definitions • Function-definition format function-name ( parameter-list ) { Declarations and

11. 4 Function Definitions • Function-definition format function-name ( parameter-list ) { Declarations and Statements } – Function name - any valid identifier – Parameter list - comma-separated list containing names of parameters received by the function when it is called – If function does not receive values, parameter-list is left empty 2000 Deitel & Associates, Inc. All rights reserved.

11. 4 Function Definitions (II) • Function body or block: – declarations and statements

11. 4 Function Definitions (II) • Function body or block: – declarations and statements within braces • Control – Returned to the point at which function was called – If function does not return a result 1. When right-brace is reached return statement is executed – If function returns a result 3. When return expression; is executed • Returns value of expressions to caller • One argument in function call for each parameter in function definition 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 2: Square. Int. html --> <HEAD> <TITLE>A Programmer-Defined square Function </TITLE> <SCRIPT LANGUAGE = "Java. Script"> document. writeln( "<H 1>Square the numbers from 1 to 10</H 1>" ); // 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 function's body is executed only // when the function is explicitly called. // square function definition function square( y ) { return y * y; } </SCRIPT> </HEAD><BODY></BODY> </HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Output HTML 2. 1 Open for control structure 2. 2 Call square userdefined function 3. 1 Define square function 3. 2 Return result

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

11. 4 Function Definitions (II) • Method Math. max( y, z ) – Returns

11. 4 Function Definitions (II) • Method Math. max( y, z ) – Returns larger of the two values inputted • When writing a function, do not – Forget to return a value if function is supposed to return a value – Forget to surround the function body with braces – Pass an argument to function that is not compatible with expected data type 2000 Deitel & Associates, Inc. All rights reserved.

1 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2 <HTML>

1 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2 <HTML> 3 <!-- Fig. 11. 3: maximum. html --> 4 5 <HEAD> 6 <TITLE>Finding the Maximum of Three Values </TITLE> 7 8 <SCRIPT LANGUAGE = "Java. Script"> 9 var input 1 = window. prompt( "Enter first number", "0" ); 10 var input 2 = window. prompt( "Enter second number", "0" ); 11 var input 3 = window. prompt( "Enter third number", "0" ); 12 13 var value 1 = parse. Float( input 1 ); 14 var value 2 = parse. Float( input 2 ); 15 var value 3 = parse. Float( input 3 ); 16 17 var max. Value = maximum( value 1, value 2, value 3 ); 18 19 document. writeln( "First number: " + value 1 + 20 "<BR>Second number: " + value 2 + 21 "<BR>Third number: " + value 3 + 22 "<BR>Maximum is: " + max. Value ); 23 24 // maximum method definition (called from line 17) 25 function maximum( x, y, z ) 26 { 27 return Math. max( x, Math. max( y, z ) ); 28 } 29 </SCRIPT> 30 31 </HEAD> 32 <BODY> 33 <P>Click Refresh (or Reload) to run the script again </P> 34 </BODY> 2000 Deitel & Associates, Inc. All rights reserved. 35 </HTML> Outline 1. 1 Define variables and prompt user for values 1. 2 Convert strings to integers 2. 1 Execute userdefined function max. Value 3. 1 Print results 4. 1 Define function max. Value

User Input Script Output 2000 Deitel & Associates, Inc. All rights reserved.

User Input Script Output 2000 Deitel & Associates, Inc. All rights reserved.

11. 5 Random Number Generation • Commonly used in simulations and gaming • Method

11. 5 Random Number Generation • Commonly used in simulations and gaming • Method Math. random – Returns floating-point value between 0 and 1, inclusive – Every value in the range has an equal chance (or probability) of being chosen each time random called • Math. floor( argument ); – Rounds down the argument to the next integer 2000 Deitel & Associates, Inc. All rights reserved.

11. 5 Random Number Generation • Random numbers Format for range of consecutive integers:

11. 5 Random Number Generation • Random numbers Format for range of consecutive integers: – For a value in a specific range of consecutive integers, use following format: Math. floor( a + Math. random() * b ); – a is the shifting value • Equal to the first number in the desired range – b is the scaling factor • Equal to the width of the desired range – Also possible to choose from sets of values other than ranges of consecutive integers 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 4: Random. Int. java --> <HEAD> <TITLE>Shifted and Scaled Random Integers </TITLE> <SCRIPT LANGUAGE = "Java. Script"> var value; document. writeln( "<H 1>Random Numbers</H 1>" + "<TABLE BORDER = '1' WIDTH = '50%'><TR>" ); for ( var i = 1; i <= 20; i++ ) { value = Math. floor( 1 + Math. random() * 6 ); document. writeln( "<TD>" + value + "</TD>" ); if ( i % 5 == 0 && i != 20 ) document. writeln( "</TR><TR>" ); Outline 1. 1 Initialize variable 2. 1 Initialize HTML TABLE 3. 1 Start for structure 3. 2 Set value to random value 3. 2. 1 Call Math. random } document. writeln( "</TR></TABLE>" ); </SCRIPT> </HEAD> <BODY> <P>Click Refresh (or Reload) to run the script again </P> </BODY> </HTML> 2000 Deitel & Associates, Inc. All rights reserved. 3. 2. 2 Set desired range for random number generation 3. 3. 3 Call Math. floor 4. 1 Print results

Script Outputs 2000 Deitel & Associates, Inc. All rights reserved.

Script Outputs 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 5: Roll. Die. html --> Outline <HEAD> <TITLE>Roll a Six-Sided Die 6000 Times </TITLE> 1. 1 Initialize variable and set values <SCRIPT LANGUAGE = "Java. Script"> var frequency 1 = 0, frequency 2 = 0, frequency 3 = 0, frequency 4 = 0, frequency 5 = 0, frequency 6 = 0, face; 2. 1 Start for structure // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math. floor( 1 + Math. random() * 6 ); switch ( face ) { case 1: ++frequency 1; break; case 2: ++frequency 2; break; case 3: ++frequency 3; break; case 4: ++frequency 4; break; case 5: ++frequency 5; break; case 6: 2000 Deitel & Associates, Inc. All rights reserved. 2. 2 set face to random integer between 1 -6 3. 1 Start switch structure 3. 2 Enter case for every possible dice roll

34 35 36 37 38 39 40 41 42 43 44 45 46 47

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 ++frequency 6; break; } } document. writeln( "<TABLE BORDER = '1' WIDTH = '50%'>" ); document. writeln( "<TR><TD><B>Face</B></TD>" + "<TD><B>Frequency</B></TD></TR>" ); document. writeln( "<TR><TD>1</TD><TD>" + frequency 1 + "</TD></TR>" ); document. writeln( "<TR><TD>2</TD><TD>" + frequency 2 + "</TD></TR>" ); document. writeln( "<TR><TD>3</TD><TD>" + frequency 3 + "</TD></TR>" ); document. writeln( "<TR><TD>4</TD><TD>" + frequency 4 + "</TD></TR>" ); document. writeln( "<TR><TD>5</TD><TD>" + frequency 5 + "</TD></TR>" ); document. writeln( "<TR><TD>6</TD><TD>" + frequency 6 + "</TD></TR></TABLE>" ); </SCRIPT> </HEAD> <BODY> <P>Click Refresh (or Reload) to run the script again </P> </BODY> </HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 4. 1 Close switch structure 4. 2 Close for structure 5. 1 Print results in HTML TABLE

Script Output from First Execution 2000 Deitel & Associates, Inc. All rights reserved.

Script Output from First Execution 2000 Deitel & Associates, Inc. All rights reserved.

Script Output from Second Execution 2000 Deitel & Associates, Inc. All rights reserved.

Script Output from Second Execution 2000 Deitel & Associates, Inc. All rights reserved.

11. 6 Example: A Game of Chance • Program can also receive input from

11. 6 Example: A Game of Chance • Program can also receive input from user through forms (discussed in HTML chapters) • GUI - Graphical User Interface – Any user interaction with a GUI is called an event – Event handling – Java. Script execution in response to an event – GUI’s are located in the BODY of the HTML document 2000 Deitel & Associates, Inc. All rights reserved.

11. 6 Example: A Game of Chance (II) GUI Setup: – GUI is enclosed

11. 6 Example: A Game of Chance (II) GUI Setup: – GUI is enclosed inside an HTML Form <FORM NAME=“form. Name”>…<FORM> tags – Every GUI output is defined with the INPUT element <INPUT NAME = “input. Name” TYPE = “text”> – Enter as many <INPUT> tags as needed – Clicking on GUI button element causes an action <INPUT TYPE = “button” VALUE = “button. Label” ONCLICK = “java. Script. Function. Name”> • Function indicated executed when button clicked 2000 Deitel & Associates, Inc. All rights reserved.

11. 6 Example: A Game of Chance (III) GUI Setup (II) • Output data

11. 6 Example: A Game of Chance (III) GUI Setup (II) • Output data to form elements – Within a function, write a statement in the following format: form. Name. input. Name. value = variable. To. Be. Output; • Browser status bar – Print text by typing window. status = “text to be printed”; – GUI’s can also be used for user input (discussed in 11. 10) 2000 Deitel & Associates, Inc. All rights reserved.

11. 6 Example: A Game of Chance (IV) • Rules of “craps” – Player

11. 6 Example: A Game of Chance (IV) • Rules of “craps” – Player rolls 2 dice (6 faces/die, range: 1 -6) – Sum of spots on two upward faces calculate • If sum equals 7 or 11 – player wins • If sum equals 2, 3 or 12 on first throw (called “craps”) – player loses • If sum equals 4, 5, 6, 8, 9 or 10 on first throw – is players “point” – If game not over after first roll, player continues rolling • If rolls sum equal to his “point” – player wins • if rolls 7 before matching his “point” – player loses – Player continues rolling until game over 2000 Deitel & Associates, Inc. All rights reserved. sum

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 6: Craps. html --> <HEAD> <TITLE>Program that Simulates the Game of Craps </TITLE> <SCRIPT LANGUAGE = "Java. Script"> // variables used to test the state of the game var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; // other variables used in program var first. Roll = true, // true if first roll sum. Of. Dice = 0, // sum of the dice my. Point = 0, // point if no win/loss on first roll game. Status = CONTINUE_ROLLING; // game not over yet // process one roll of the dice function play() { if ( first. Roll ) { sum. Of. Dice = roll. Dice(); // first roll of the dice switch ( sum. Of. Dice ) { case 7: case 11: game. Status = WON; craps. point. value = ""; break; case 2: case 3: case 12: game. Status = LOST; craps. point. value = ""; break; default: 2000 Deitel & Associates, Inc. All rights reserved. // win on first roll // clear point field // lose on first roll // clear point field // remember point Outline 1. 1 Initialize variables and set values 2. 1 Define function play() 2. 2 Start if structure 2. 3 Start switch structure 2. 4 Define switch case actions 2. 4. 1 Print values of dice rolled

34 35 36 37 38 39 40 41 42 43 44 45 46 47

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 game. Status = CONTINUE_ROLLING; my. Point = sum. Of. Dice; craps. point. value = my. Point; first. Roll = false; } } else { sum. Of. Dice = roll. Dice(); if ( sum. Of. Dice == my. Point ) game. Status = WON; else if ( sum. Of. Dice == 7 ) game. Status = LOST; // win by making point if ( game. Status == CONTINUE_ROLLING ) window. status = "Roll again"; else { if ( game. Status == WON ) window. status = "Player wins. " + "Click Roll Dice to play again. "; else window. status = "Player loses. " + "Click Roll Dice to play again. "; } } // roll the dice function roll. Dice() { 2000 Deitel & Associates, Inc. All rights reserved. 2. 5 Plan all possible dice rolls 2. 6 Plan for player to continue rolling indefinitely // lose by rolling 7 } first. Roll = true; Outline 3. 1 Define function roll. Dice()

67 var die 1, die 2, work. Sum; 68 69 die 1 = Math.

67 var die 1, die 2, work. Sum; 68 69 die 1 = Math. floor( 1 + Math. random() * 6 ); 70 die 2 = Math. floor( 1 + Math. random() * 6 ); 71 work. Sum = die 1 + die 2; 72 73 craps. first. Die. value = die 1; 74 craps. second. Die. value = die 2; 75 craps. sum. value = work. Sum; 76 77 return work. Sum; 78 } 79</SCRIPT> 80 81</HEAD> 82<BODY> 83<FORM NAME = "craps"> 84 <TABLE BORDER = "1"> 85 <TR><TD>Die 1</TD> 86 <TD><INPUT NAME = "first. Die" TYPE = "text"></TD></TR> 87 <TR><TD>Die 2</TD> 88 <TD><INPUT NAME = "second. Die" TYPE = "text"></TD></TR> 89 <TR><TD>Sum</TD> 90 <TD><INPUT NAME = "sum" TYPE = "text"></TD></TR> 91 <TR><TD>Point</TD> 92 <TD><INPUT NAME = "point" TYPE = "text"></TD></TR> 93 <TR><TD><INPUT TYPE = "button" VALUE = "Roll Dice" 94 ONCLICK = "play()"></TD></TR> 95 </TABLE> 96</FORM> 97</BODY> 98</HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. 2 Calculate random dice rolls 3. 3 Print dice rolls 3. 4 Return dice value to function call 4. 1 Set FORM GUI structure 4. 2 Define INPUT fields 4. 3 Define BUTTON element and ONCLICK attribute

Script Output 1 (player wins first roll) 2000 Deitel & Associates, Inc. All rights

Script Output 1 (player wins first roll) 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2 (player loses first roll) 2000 Deitel & Associates, Inc. All rights

Script Output 2 (player loses first roll) 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 3 (player wins on second roll) Roll 1 Roll 2 2000 Deitel

Script Output 3 (player wins on second roll) Roll 1 Roll 2 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 4 (player loses on second roll) Roll 1 Roll 2 2000 Deitel

Script Output 4 (player loses on second roll) Roll 1 Roll 2 2000 Deitel & Associates, Inc. All rights reserved.

11. 7 Duration of Identifiers • Each identifier has duration and scope – Duration

11. 7 Duration of Identifiers • Each identifier has duration and scope – Duration (or lifetime) is the period during which identifier exists in memory. • Some identifiers exist briefly • Some identifiers are repeatedly created and destroyed • Some identifiers exist for entire execution of the program • Identifiers which represent local variables in a function have automatic duration – – Automatically created when program control enters function Exist while function is active Automatically destroyed when function is exited Referred to as local variables 2000 Deitel & Associates, Inc. All rights reserved.

11. 7 Duration of Identifiers (II) • Java. Script also has identifiers of static

11. 7 Duration of Identifiers (II) • Java. Script also has identifiers of static duration – Typically defined in <HEAD> section of HTML document – Exist from point at which declared until browsing session over – Even though they exist after <HEAD> section terminates, cannot necessarily be used throughout the script – Referred to as global variables or script-level variables 2000 Deitel & Associates, Inc. All rights reserved.

11. 8 Scope Rules • Scope of identifier is portion of program in which

11. 8 Scope Rules • Scope of identifier is portion of program in which identifier can be referenced – Local variable declared in a function can be used only in that function • Identifiers declared inside a function have function (or local) scope – – Begins with opening brace ({) of function Ends with closing brace(}) of function Function parameters also have local scope If local variable has same name as global variable, global variable “hidden” from body of function 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 7: scoping. html --> <HEAD> <TITLE>A Scoping Example</TITLE> <SCRIPT LANGUAGE = "Java. Script"> var x = 1; // global variable function start() { var x = 5; // variable local to function start document. writeln( "local x in start is " + x ); function. A(); function. B(); // // function. A has local x function. B uses global variable x function. A reinitializes local x global variable x retains its value document. writeln( "<P>local x in start is " + x + "</P>" ); } 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Initialize variable 2. 1 Define start() function 2. 2 State start function actions 2. 3 Call user defined functions 2. 4 Print results

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 function. A() { var x = 25; // initialized each time function. A is called document. writeln( "<P>local x in function. A is " + x + " after entering function. A" ); ++x; document. writeln( "<BR>local x in function. A is " + x + " before exiting function. A</P>" ); } function. B() { document. writeln( "<P>global variable x is " + x + " on entering function. B" ); x *= 10; document. writeln( "<BR>global variable x is " + x + " on exiting function. B</P>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "start()"></BODY> </HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. 1 Define function. A() 3. 2 Demonstrate function scope 4. 1 Define function. B() 4. 2 Demonstrate global scope

Script Output: 2000 Deitel & Associates, Inc. All rights reserved.

Script Output: 2000 Deitel & Associates, Inc. All rights reserved.

11. 9 Recursion • Recursive function – A function that calls itself directly, or

11. 9 Recursion • Recursive function – A function that calls itself directly, or indirectly through another function • Process 1. 2. 3. 4. Function called on to solve problem Function knows how to solve most simple case (base case) If called with base case, returns result If called with more complex case 2000 Deitel & Associates, Inc. All rights reserved.

11. 9 Recursion • Process 5. Function divides problem into two conceptual pieces: 1.

11. 9 Recursion • Process 5. Function divides problem into two conceptual pieces: 1. Piece function knows how to do 2. Piece function does not know how to do • Resembles original problem, but is slightly simpler or smaller 6. Function makes recursive call • • • Invokes fresh copy of itself to work on smaller problem Normally includes keyword return Send result back to previous copy of itself that made the recursive call 2000 Deitel & Associates, Inc. All rights reserved.

11. 9 Recursion (II) • Process 7. Recursion step executes while original function still

11. 9 Recursion (II) • Process 7. Recursion step executes while original function still open 1. Can result in additional recursive calls being made as function keeps dividing problem 8. Recursion termination: 1. Eventually, after a number of recursive calls, function recognizes base case 1. Returns value to copy of function that called it 2. Continues until original function returns final result 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 9: Factorial. Test. html --> <HEAD> <TITLE>Recursive Factorial Function </TITLE> Outline 1. 1 Open HTML TABLE 2. 1 Open for structure <SCRIPT LANGUAGE = "Java. Script"> document. writeln( "<H 1>Factorials of 1 to 10</H 1>" ); 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>" ); 2. 2 Call factorial function 3. 1 Define factorial function document. writeln( "</TABLE>" ); // Recursive definition of function factorial( number ) { if ( number <= 1 ) // base case return 1; else return number * factorial( number - 1 ); } </SCRIPT> </HEAD><BODY></BODY> </HTML> 2000 Deitel & Associates, Inc. All rights reserved. 3. 2 Make recursive call statement

Script Output: 2000 Deitel & Associates, Inc. All rights reserved.

Script Output: 2000 Deitel & Associates, Inc. All rights reserved.

11. 9 Recursion (II) Recursive Evaluation of 5! Final Value = 120 5! 5!

11. 9 Recursion (II) Recursive Evaluation of 5! 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 Procession of recursive calls 2000 Deitel & Associates, Inc. All rights reserved. 1 Values returned from each recursive call

11. 10 Example of Using Recursion: The Fibonacci Series • GUI input setup: –

11. 10 Example of Using Recursion: The Fibonacci Series • GUI input setup: – All user inputs (if there any) are defined by HTML INPUT tag <INPUT NAME = “input. Name” TYPE = “text”> – Enter as many inputs as you want, giving each an applicable name – The form button component allows the user to send his inputted information to the server <INPUT TYPE = “button” VALUE = “button. Label” ONCLICK = “java. Script. Function. Call”> – Function called in ONCLICK element is executed when event is executed – Function called in GUI will execute using FORM elements as its parameters 2000 Deitel & Associates, Inc. All rights reserved.

11. 10 Example of Using Recursion: The Fibonacci Series (II) • Fibonacci series: –

11. 10 Example of Using Recursion: The Fibonacci Series (II) • Fibonacci series: – 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89… – Begins with 0 and 1 – Each number is sum of pervious two numbers • May be defined recursively as: – fibonacci( 0 ) = 0 – fibonacci( 1 ) = 1 – fibonacci( n ) = fibonacci( n - 1 ) + fibonacci( n - 2) • Ratio of successive numbers converges on 1. 618… – Golden ratio or golden mean • Avoid programs with Fibonacci-style calls – Results in exponential “explosion” of calls 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > <HTML> <!-- Fig. 11. 10: Fibonacci. Test. html --> <HEAD> <TITLE>Recursive Fibonacci Function </TITLE> <SCRIPT LANGUAGE = "Java. Script"> // Event handler for button HTML component in my. Form function get. Fibonacci. Value() { var value = parse. Int( document. my. Form. number. value ); window. status = "Calculating Fibonacci number for " + value; document. my. Form. result. value = fibonacci( value ); window. status = "Done calculating Fibonacci number"; } // Recursive definition of function fibonacci( n ) { if ( n == 0 || n == 1 ) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } </SCRIPT> </HEAD> 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Define function: get. Fibonacci. Value 1. 2 Define variable from user input 1. 3 Print results 2. 1 Define function: fibonacci 2. 2 Make recursive calls 2. 3 Return result

31<BODY> 32<FORM NAME = "my. Form"> 33 <TABLE BORDER = "1"> 34 <TR><TD>Enter an

31<BODY> 32<FORM NAME = "my. Form"> 33 <TABLE BORDER = "1"> 34 <TR><TD>Enter an integer</TD> 35 <TD><INPUT NAME = "number" TYPE = "text"></TD> 36 <TD><INPUT TYPE = "button" VALUE = "Calculate" 37 38 ONCLICK = "get. Fibonacci. Value()"</TR> <TR><TD>Fibonacci value</TD> 39 40 <TD><INPUT NAME = "result" TYPE = "text"></TD></TR> </TABLE> 41</FORM></BODY> 42</HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Open <FORM> 1. 2 Open <TABLE> 1. 3 Insert <INPUT> elements with appropriate attributes 1. 4 Close </FORM> and </TABLE>

Script Outputs: 2000 Deitel & Associates, Inc. All rights reserved.

Script Outputs: 2000 Deitel & Associates, Inc. All rights reserved.

11. 10 Example of Using Recursion: The Fibonacci Series Set of Recursive Calls to

11. 10 Example of Using Recursion: The Fibonacci Series Set of Recursive Calls to Function fibonacci f( 3 ) return f( 1 ) f( 2 ) + return 1 2000 Deitel & Associates, Inc. All rights reserved. + f( 0 ) return 0 f( 1 ) return 1

11. 11 Recursion vs. Iteration • Common Aspects – Both based on a control

11. 11 Recursion vs. Iteration • Common Aspects – Both based on a control structure • Recursion uses a selection structure • Iteration uses a repetition structure – Both involve repetition – Both involve termination test – Iteration with counter-controlled repetition and recursion both gradually approach termination – Both can occur infinitely 2000 Deitel & Associates, Inc. All rights reserved.

11. 11 Recursion vs. Iteration (II) • Negatives of recursion – Repeatedly invokes mechanism

11. 11 Recursion vs. Iteration (II) • Negatives of recursion – Repeatedly invokes mechanism or function calls – Expensive in processor time and memory space • Each recursive call causes copy of itself to be made – Iteration normally occurs within a function so overhead of repeated calls is omitted • Why choose recursion over iteration? – Good software engineering important – High performance important – Have to find the right mix between the two depending on the situation 2000 Deitel & Associates, Inc. All rights reserved.

11. 12 Java. Script Global Functions • Global functions are part of Java. Script’s

11. 12 Java. Script Global Functions • Global functions are part of Java. Script’s Global object – Contains all global variables in the script – Some programmers refer to these functions as methods • • Global functions and user-defined functions part of Global object You do not need to use the Global object directly – Java. Script does this for you 2000 Deitel & Associates, Inc. All rights reserved.

11. 12 Java. Script Global Functions (II) • Global Functions 1. escape • •

11. 12 Java. Script Global Functions (II) • Global Functions 1. escape • • Takes string argument and returns string in which all spaces, punctuation, accent characters and all other non-ASCII characters are encoded in hexadecimal form Can be represented on all platforms 2. eval • • Takes string argument representing Java. Script code to execute. Evaluates code and executes it when eval function is called Allows Java. Script code to be stored as strings and executed dynamically 3. is. Finite • • Takes numeric argument and returns true if value is not Na. N, Number. POSITIVE_INFINITY or Number. NEGATIVE_INFINITY Otherwise function returns false 2000 Deitel & Associates, Inc. All rights reserved.

11. 12 Java. Script Global Functions (III) • Global Functions (continued) 4. is. Na.

11. 12 Java. Script Global Functions (III) • Global Functions (continued) 4. is. Na. N • • • Takes numeric argument and returns true if value is not a number Otherwise returns false Commonly used with return value of parse. Int and parse. Float to determine whether result is proper numeric value 5. parse. Float • • • Takes string argument and converts beginning of string to floatingpoint value If conversion unsuccessful, returns Na. N Otherwise, returns converted value 2000 Deitel & Associates, Inc. All rights reserved.

11. 12 Java. Script Global Functions (IV) • Global Functions (continued) 6. parse. Int

11. 12 Java. Script Global Functions (IV) • Global Functions (continued) 6. parse. Int • • Takes string argument and attempts to convert beginning of string into integer value If conversion not successful, returns Na. N Otherwise, returns converted value Takes an optional second argument between 2 and 36 specifying the radix (or base) of the number 7. unescape • Takes a string and returns string in which all characters previously encoded with escape are decoded 2000 Deitel & Associates, Inc. All rights reserved.