The document discusses JavaScript functions and modules. It covers defining functions, passing arguments to functions, and function scope. Examples are provided to demonstrate programming techniques like defining functions to square numbers, find the maximum of three values, and generate random numbers. The use of functions in simulating games of chance is also explained.
ECS 40 Program #3 (50 points, my time 1.5 hours) Spring 2015 .docxjack60216
ECS 40 Program #3 (50 points, my time 1.5 hours) Spring 2015
Due: Wednesday, April 29th at 11:59pm using handin to p3 directory of cs40a.
New concepts: iostream, fstream, new, delete, and C++ . Name of executable: simulator.out
File names: Makefile, main.cpp, city.cpp, city.h, vector.cpp, vector.h, authors.txt.
For this assignment, you will 1) adapt your code to data files that have more than one city with the same name, 2)
converting your C code of p2 to C++, and 3) you will add the ability to list all of the traffic from a specific airport.
Adapting to the duplicated city names, should only involve readAirports(), readAirport(), and isEqual(), and is fairly
straightforward for each (total 5 minutes). Converting to C++ will involve: 1) replacing stdio.h function calls with
iostream and fstream function calls; 2) replacing malloc and free with new and delete; 3) removing #include of stdio.h,
and replace #includes of other C header files with their C++ counterparts; 4) changing the Vector struct to a Vector class;
and 5) changing the City struct to a City class. Listing airport traffic involves adding a getChoic() function to main.cpp
and a new method to Vector.
You may use either your own p1 code, or my p1 code from ~ssdavis/40/p1/SeansSrc (available Thursday morning) as
your starting point for the assignment. There is no problem with plagiarism if you use my code. You will find my
executable, and the two data files in ~ssdavis/40/p3. As usual, the format and values of your program must match mine.
To get traffic value into a more reasonable range you will now divide by 2500000000U instead of 250000000U.
Here is a road map to making the transitions. After each of the five steps your program should compile with no
warnings, and run perfectly. The road map is based on my own program, so you may wish to have my program handy
even if you are modifying your own p1.
1. Replacing stdio.h function calls with iostream and fstream function calls. (10 minutes)
1.1. Replace printf with cout statements.
1.2. Replace scanf with cin statements.
1.3. Replace FILE* declarations and assignments with ifstream declarations.
1.3.1. An ifstream may only be passed by reference.
1.4. Replace fgets with getline. Note that getline does not place the '\n' in the array.
1.5. Don't forget to add "using namespace std;" to any files with C++ header files.
2. Replacing malloc and free with new and delete. (5 minutes)
2.1. Remember to use delete [] to deallocate arrays.
3. Change all input/output to C++, and update standard header file #includes to C++ format. (15 minutes)
3.1. Remove stdio.h #includes, and add iostream and fstream includes only where appropriate.
3.2. Remember to add “using namespace std;” below the #include lists.
3.3. Change fopen() to an ifstream constructor, printf() to cout <<, scanf to cin >>, and fgets() to getline().
3.4. Change all remaining #includes involving < > from < ...
Deep Dive Into Catalyst: Apache Spark 2.0’s OptimizerDatabricks
Catalyst is becoming one of the most important components in Apache Spark, as it underpins all the major new APIs in Spark 2.0, from DataFrames, Datasets, to streaming. At its core, Catalyst is a general library for manipulating trees. Based on this library, we have built a modular compiler frontend for Spark, including a query analyzer, optimizer, and an execution planner. In this talk, I will first introduce the concepts of Catalyst trees, followed by major features that were added in order to support Spark’s powerful API abstractions. Audience will walk away with a deeper understanding of how Spark 2.0 works under the hood.
Testing the Numerical Precisions Required to Execute Real World Programs ijseajournal
The IEEE 754 Standard for floating point number formats is over 30 years old. Computational
requirements have changed dramatically during these 30 years. This paper describes methods by which,
for a given program required to yield results of a given accuracy, one may determine:
1) whether the choices of numerical precision are adequate;
2) the minimum numerical precisions actually required;
3) the statements most vulnerable to loss of precision.
Precision is specified as an exact number of mantissa bits for each real kind.
The method is applied to two small Fortran simulation programs with surprising results. The implications
are that considerable savings could be made in computer hardware by computing with reduced precision,
and that speed improvements may be made on existing systems by packing data for inter-processor
communication, removing those parts of the bit patterns which are not needed.
Computer Science CS Project Matrix CBSE Class 12th XII .pdfPranavAnil9
The following project is based on Matrices and Determinants. It is a menu based program with data file and SQL Connectivity. The program is capable of performing all the complex functions of matrices and determinants that are mentioned in the Class 12th Math’s book. The ‘Menu’ of the program upon which it executes is as follows:
1: Generate a Random Matrix
2: Addition
3: Subtraction
4: Multiplication by a Scalar
5: Multiplication by a Matrix
6: Calculate Determinant
7: Calculate Minor
8: Calculate Cofactor
9: Calculate Adjoint
10: Transpose
11: Inversion
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
ECS 40 Program #3 (50 points, my time 1.5 hours) Spring 2015 .docxjack60216
ECS 40 Program #3 (50 points, my time 1.5 hours) Spring 2015
Due: Wednesday, April 29th at 11:59pm using handin to p3 directory of cs40a.
New concepts: iostream, fstream, new, delete, and C++ . Name of executable: simulator.out
File names: Makefile, main.cpp, city.cpp, city.h, vector.cpp, vector.h, authors.txt.
For this assignment, you will 1) adapt your code to data files that have more than one city with the same name, 2)
converting your C code of p2 to C++, and 3) you will add the ability to list all of the traffic from a specific airport.
Adapting to the duplicated city names, should only involve readAirports(), readAirport(), and isEqual(), and is fairly
straightforward for each (total 5 minutes). Converting to C++ will involve: 1) replacing stdio.h function calls with
iostream and fstream function calls; 2) replacing malloc and free with new and delete; 3) removing #include of stdio.h,
and replace #includes of other C header files with their C++ counterparts; 4) changing the Vector struct to a Vector class;
and 5) changing the City struct to a City class. Listing airport traffic involves adding a getChoic() function to main.cpp
and a new method to Vector.
You may use either your own p1 code, or my p1 code from ~ssdavis/40/p1/SeansSrc (available Thursday morning) as
your starting point for the assignment. There is no problem with plagiarism if you use my code. You will find my
executable, and the two data files in ~ssdavis/40/p3. As usual, the format and values of your program must match mine.
To get traffic value into a more reasonable range you will now divide by 2500000000U instead of 250000000U.
Here is a road map to making the transitions. After each of the five steps your program should compile with no
warnings, and run perfectly. The road map is based on my own program, so you may wish to have my program handy
even if you are modifying your own p1.
1. Replacing stdio.h function calls with iostream and fstream function calls. (10 minutes)
1.1. Replace printf with cout statements.
1.2. Replace scanf with cin statements.
1.3. Replace FILE* declarations and assignments with ifstream declarations.
1.3.1. An ifstream may only be passed by reference.
1.4. Replace fgets with getline. Note that getline does not place the '\n' in the array.
1.5. Don't forget to add "using namespace std;" to any files with C++ header files.
2. Replacing malloc and free with new and delete. (5 minutes)
2.1. Remember to use delete [] to deallocate arrays.
3. Change all input/output to C++, and update standard header file #includes to C++ format. (15 minutes)
3.1. Remove stdio.h #includes, and add iostream and fstream includes only where appropriate.
3.2. Remember to add “using namespace std;” below the #include lists.
3.3. Change fopen() to an ifstream constructor, printf() to cout <<, scanf to cin >>, and fgets() to getline().
3.4. Change all remaining #includes involving < > from < ...
Deep Dive Into Catalyst: Apache Spark 2.0’s OptimizerDatabricks
Catalyst is becoming one of the most important components in Apache Spark, as it underpins all the major new APIs in Spark 2.0, from DataFrames, Datasets, to streaming. At its core, Catalyst is a general library for manipulating trees. Based on this library, we have built a modular compiler frontend for Spark, including a query analyzer, optimizer, and an execution planner. In this talk, I will first introduce the concepts of Catalyst trees, followed by major features that were added in order to support Spark’s powerful API abstractions. Audience will walk away with a deeper understanding of how Spark 2.0 works under the hood.
Testing the Numerical Precisions Required to Execute Real World Programs ijseajournal
The IEEE 754 Standard for floating point number formats is over 30 years old. Computational
requirements have changed dramatically during these 30 years. This paper describes methods by which,
for a given program required to yield results of a given accuracy, one may determine:
1) whether the choices of numerical precision are adequate;
2) the minimum numerical precisions actually required;
3) the statements most vulnerable to loss of precision.
Precision is specified as an exact number of mantissa bits for each real kind.
The method is applied to two small Fortran simulation programs with surprising results. The implications
are that considerable savings could be made in computer hardware by computing with reduced precision,
and that speed improvements may be made on existing systems by packing data for inter-processor
communication, removing those parts of the bit patterns which are not needed.
Computer Science CS Project Matrix CBSE Class 12th XII .pdfPranavAnil9
The following project is based on Matrices and Determinants. It is a menu based program with data file and SQL Connectivity. The program is capable of performing all the complex functions of matrices and determinants that are mentioned in the Class 12th Math’s book. The ‘Menu’ of the program upon which it executes is as follows:
1: Generate a Random Matrix
2: Addition
3: Subtraction
4: Multiplication by a Scalar
5: Multiplication by a Matrix
6: Calculate Determinant
7: Calculate Minor
8: Calculate Cofactor
9: Calculate Adjoint
10: Transpose
11: Inversion
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Normal Labour/ Stages of Labour/ Mechanism of LabourWasim Ak
Normal labor is also termed spontaneous labor, defined as the natural physiological process through which the fetus, placenta, and membranes are expelled from the uterus through the birth canal at term (37 to 42 weeks
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
Javascript.ppt
1. 2004 Prentice Hall, Inc. All rights reserved.
1
Chapter 10 - JavaScript: Functions
Outline
10.1 Introduction
10.2 Program Modules in JavaScript
10.3 Programmer-Defined Functions
10.4 Function Definitions
10.5 Random-Number Generation
10.6 Example: Game of Chance
10.7 Another Example: Random Image Generator
10.8 Scope Rules
10.9 JavaScript Global Functions
10.10 Recursion
10.11 Recursion vs. Iteration
10.12 Web Resources
2. 2004 Prentice Hall, Inc. All rights reserved.
2
Objectives
• In this tutorial, you will learn:
– To understand how to construct programs modularly from
small pieces called functions.
– To be able to create new functions.
– To understand the mechanisms used to pass information
between functions.
– To introduce simulation techniques that use random-number
generation.
– To understand how the visibility of identifiers is limited to
specific regions of programs.
3. 2004 Prentice Hall, Inc. All rights reserved.
3
10.1 Introduction
• Software design
– Break software up into modules
• Easier to maintain and debug
– Divide and conquer
4. 2004 Prentice Hall, Inc. All rights reserved.
4
10.2 Program Modules in JavaScript
• Modules in JavaScript
– Functions
– Methods
• Belong to an object
– JavaScript includes many useful pre-defined methods
• Combine with programmer-defined methods to make a
program
5. 2004 Prentice Hall, Inc. All rights reserved.
5
10.2 Program Modules in JavaScript
• Functions
– Started by function call
– Receive necessary information via arguments (parameters)
– Boss-Worker relationship
• Calling function
• Called function
• Return value when finished
• Can have many tiers
6. 2004 Prentice Hall, Inc. All rights reserved.
6
10.2 Program Modules in JavaScript
boss
worker1 worker2 worker3
worker4 worker5
Fig. 10.1 Hierarchical boss-function/worker-function relationship.
7. 2004 Prentice Hall, Inc. All rights reserved.
7
10.2 Program Modules in JavaScript
• Function calls
– Name
– Left parenthesis
– Arguments separated by commas
• Constants, variables or expressions
– Right parenthesis
– Examples:
total += parseFloat( inputValue );
total += parseFloat( s1 + s2 );
8. 2004 Prentice Hall, Inc. All rights reserved.
8
10.3 Programmer-Defined Functions
• Defining functions
– All variables declared in function are called local
• Do not exist outside current function
– Parameters
• Also local variables
– Promotes reusability
• Keep short
• Name clearly
9. 2004 Prentice Hall, Inc. All rights reserved.
9
10.4 Function Definitions
• Format of a function definition
function function-name( parameter-list )
{
declarations and statements
}
– Function name any valid identifier
– Parameter list names of variables that will receive arguments
• Must have same number as function call
• May be empty
– Declarations and statements
• Function body (“block” of code)
10. 2004 Prentice Hall, Inc. All rights reserved.
10
10.4 Function Definitions
• Returning control
– return statement
– Can return either nothing, or a value
return expression;
– No return statement same as return;
– Not returning a value when expected is an error
11. 2004 Prentice Hall, Inc. All rights reserved.
11
10.4 Function Definitions
• Writing a function to square two numbers
– for loop from 1 to 10
– Pass each number as argument to square
– return value of argument multiplied by itself
– Display result
12. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
12
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.2: SquareInt.html -->
6 <!-- Square function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A Programmer-Defined square Function</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.writeln(
15 "<h1>Square the numbers from 1 to 10</h1>" );
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 ) + "<br />" );
21
SquareInt.html
(1 of 2)
Calling function square and passing it the value of x.
13. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
13
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 </script>
32
33 </head><body></body>
34 </html>
SquareInt.html
(2 of 2)
Variable y gets the value of variable x.
The return statement passes the value of y * y
back to the calling function.
14. 2004 Prentice Hall, Inc. All rights reserved.
14
10.4 Function Definitions
Fig. 10.2 Using programmer-defined function square.
15. 2004 Prentice Hall, Inc. All rights reserved.
15
10.4 Function Definitions
• Finding the maximum of 3 numbers
– Prompt for 3 inputs
– Convert to numbers
– Pass to maximum
– Math.max
16. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
16
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.3: maximum.html -->
6 <!-- Maximum function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Finding the Maximum of Three Values</title>
11
12 <script type = "text/javascript">
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 );
Maximum.html
(1 of 2)
Prompt for the user to input three integers.
17. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
17
24
25 var maxValue = maximum( value1, value2, value3 );
26
27 document.writeln( "First number: " + value1 +
28 "<br />Second number: " + value2 +
29 "<br />Third number: " + value3 +
30 "<br />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 ) );
36 }
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>
Maximum.html
(2 of 2)
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.
18. 2004 Prentice Hall, Inc. All rights reserved.
18
10.4 Function Definitions
Fig. 10.3 Programmer-defined maximum function (1 of 2).
19. 2004 Prentice Hall, Inc. All rights reserved.
19
10.4 Function Definitions
Fig. 10.3 Programmer-defined maximum function (2 of 2).
20. 2004 Prentice Hall, Inc. All rights reserved.
20
10.5 Random-Number Generation
• Random-number generation introduces element of
chance
– Math.random
var randomValue = Math.random();
– Floating point value between 0 and 1
– Adjust range by scaling and shifting
– Math.floor
• Always round down
Math.floor( 1 + Math.random() * 6 )
21. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
21
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.4: RandomInt.html -->
6 <!-- Demonstrating the Random method -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Shifted and Scaled Random Integers</title>
11
12 <script type = "text/javascript">
13 <!--
14 var value;
15
16 document.writeln(
17 "<table border = "1" width = "50%">" );
18 document.writeln(
19 "<caption>Random Numbers</caption><tr>" );
20
RandomInt.html
(1 of 2)
22. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
22
21 for ( var i = 1; i <= 20; i++ ) {
22 value = Math.floor( 1 + Math.random() * 6 );
23 document.writeln( "<td>" + value + "</td>" );
24
25 // write end and start <tr> tags when
26 // i is a multiple of 5 and not 20
27 if ( i % 5 == 0 && i != 20 )
28 document.writeln( "</tr><tr>" );
29 }
30
31 document.writeln( "</tr></table>" );
32 // -->
33 </script>
34
35 </head>
36 <body>
37 <p>Click Refresh (or Reload) to run the script again</p>
38 </body>
39 </html>
RandomInt.html
(2 of 2)
The for loop creates 20
table cells (4 rows x 5
columns).
Each cell is populated
with a random number
generated by method
random.
Method floor rounds the number
generated by method random down.
23. 2004 Prentice Hall, Inc. All rights reserved.
23
10.5 Random-Number Generation
Fig. 10.4 Random integers, shifting and scaling.
24. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
24
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.5: RollDie.html -->
6 <!-- Rolling a Six-Sided Die -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Roll a Six-Sided Die 6000 Times</title>
11
12 <script type = "text/javascript">
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
RollDie.html
(1 of 3)
This expression uses method random to
generate a random number between 1 and 6.
25. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
25
RollDie.html
(2 of 3)
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:
36 ++frequency5;
37 break;
38 case 6:
39 ++frequency6;
40 break;
41 }
42 }
43
When the controlling expression, face,
matches a case label, the respective
frequency variable is incremented.
26. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
26
RollDie.html
(3 of 3)
44 document.writeln( "<table border = "1"" +
45 "width = "50%">" );
46 document.writeln( "<thead><th>Face</th>" +
47 "<th>Frequency<th></thead>" );
48 document.writeln( "<tbody><tr><td>1</td><td>" +
49 frequency1 + "</td></tr>" );
50 document.writeln( "<tr><td>2</td><td>" + frequency2 +
51 "</td></tr>" );
52 document.writeln( "<tr><td>3</td><td>" + frequency3 +
53 "</td></tr>" );
54 document.writeln( "<tr><td>4</td><td>" + frequency4 +
55 "</td></tr>" );
56 document.writeln( "<tr><td>5</td><td>" + frequency5 +
57 "</td></tr>" );
58 document.writeln( "<tr><td>6</td><td>" + frequency6 +
59 "</td></tr></tbody></table>" );
60 // -->
61 </script>
62
63 </head>
64 <body>
65 <p>Click Refresh (or Reload) to run the script again</p>
66 </body>
67 </html>
The results of rolling the die
600 times are displayed in a
table.
27. 2004 Prentice Hall, Inc. All rights reserved.
27
10.5 Random-Number Generation
Fig. 10.5 Rolling a six-sided die 6000 times.
28. 2004 Prentice Hall, Inc. All rights reserved.
28
10.6 Example: Game of Chance
• Craps
– Click Roll Dice
– Text fields show rolls, sum and point
– Status bar displays results
29. 2004 Prentice Hall, Inc. All rights reserved.
29
10.6 Example: Game of Chance
• Uses XHTML forms
– Gather multiple inputs at once
– Empty action attribute
– name attribute allows scripts to interact with form
• Event handling and event-driven programming
– Assign a function to an event
– Onclick
• Constants
– Variable that cannot be modified
– Part of many languages, not supported in JavaScript
• Name “constant” variables with all capital letters
– Make values easier to remember/change
30. 2004 Prentice Hall, Inc. All rights reserved.
30
10.6 Example: Game of Chance
• Changing properties
– Access with dot (.) notation
– value property of text fields
– status property of window
31. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
31
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- Fig. 10.6: Craps.html -->
6 <!-- Craps Program -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Program that Simulates the Game of Craps</title>
11
12 <script type = "text/javascript">
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
Craps.html
(1 of 5)
32. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
32
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
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 }
Craps.html
(2 of 5)
If the value of firstRoll is true, then function
rollDice is called.
If function rollDice returns a value of 7
or 11, the player wins and the break
statement causes program control
proceeds to the first line after the switch
structure.
If function rollDice returns a 2, 3 or 12, the
player loses and the break statement causes
control to proceed to first line after the switch
structure.
33. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
33
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
Craps.html
(3 of 5)
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.
If the value of firstRoll is false,
function rollDice is called to see if the
point has been reached.
34. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
34
Craps.html
(4 of 5)
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 </script>
88
89 </head>
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 values of
the dice are placed in their respective
form fields.
35. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
35
Craps.html
(5 of 5)
90 <body>
91 <form name = "craps" action = "">
92 <table border = "1">
93 <caption>Craps</caption>
94 <tr><td>Die 1</td>
95 <td><input name = "firstDie" type = "text" />
96 </td></tr>
97 <tr><td>Die 2</td>
98 <td><input name = "secondDie" type = "text" />
99 </td></tr>
100 <tr><td>Sum</td>
101 <td><input name = "sum" type = "text" />
102 </td></tr>
103 <tr><td>Point</td>
104 <td><input name = "point" type = "text" />
105 </td></tr>
106 <tr><td><input type = "button" value = "Roll Dice"
107 onclick = "play()" /></td></tr>
108 </table>
109 </form>
110 </body>
111 </html>
36. 2004 Prentice Hall, Inc. All rights reserved.
36
10.6 Example: Game of Chance
Fig. 10.6 Craps game simulation.
A text XHTML GUI component
A button XHTML GUI component
Browser’s status bar
37. 2004 Prentice Hall, Inc. All rights reserved.
37
10.6 Example: Game of Chance
Fig. 10.6 Craps game simulation.
38. 2004 Prentice Hall, Inc. All rights reserved.
38
10.6 Example: Game of Chance
Fig. 10.6 Craps game simulation.
39. 2004 Prentice Hall, Inc. All rights reserved.
39
10.7 Another Example: Random Image
Generator
• Randomly selecting an image
– Images have integer names (i.e., 1.gif, 2.gif, …, 7.gif)
– Generate random number in proper range
– Update src property
40. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
40
RandomPicture.html
(1 of 1)
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 10.7: RandomPicture.html -->
6 <!-- Randomly displays one of 7 images -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Random Image Generator</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.write ( "<img src = "" +
15 Math.floor( 1 + Math.random() * 7 ) +
16 ".gif" width = "105" height = "100" />" );
17 // -->
18 </script>
19
20 </head>
21
22 <body>
23 <p>Click Refresh (or Reload) to run the script again</p>
24 </body>
25 </html>
Inserting a random number into the image’s src
property with document.write and Math.random
41. 2004 Prentice Hall, Inc. All rights reserved.
41
10.7 Another Example: Random Image
Generator
Fig. 10.7 Random image generation using Math.random.
42. 2004 Prentice Hall, Inc. All rights reserved.
42
10.8 Scope Rules
• Scope
– Portion of program where identifier can be referenced
– Inside function is local or function scope
• Identifiers exist only between opening and closing braces
• Local variables hide global variables
43. 2004 Prentice Hall, Inc. All rights reserved.
43
10.8 Scope Rules
• Scope demonstration
– Global variable x initialized to 1
– start has local variable x initialized to 5
– functionA has local variable x initialized to 25
– functionB has no local variable x
– Observe output of each function
44. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
44
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.8: scoping.html -->
6 <!-- Local and Global Variables -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A Scoping Example</title>
11
12 <script type = "text/javascript">
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
Scoping.html
(1 of 3)
To begin the program, variable x is initialized to 1.
Function start changes the value of x to 5.
45. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
45
Scoping.html
(2 of 3)
26
27 document.writeln(
28 "<p>local x in start is " + x + "</p>" );
29 }
30
31 function functionA()
32 {
33 var x = 25; // initialized each time
34 // functionA is called
35
36 document.writeln( "<p>local x in functionA is " +
37 x + " after entering functionA" );
38 ++x;
39 document.writeln( "<br />local x in functionA is " +
40 x + " before exiting functionA" + "</p>" );
41 }
42
Function functionA changes the value of x to 25.
The value of x is incremented.
46. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
46
Scoping.html
(3 of 3)
43 function functionB()
44 {
45 document.writeln( "<p>global variable x is " + x +
46 " on entering functionB" );
47 x *= 10;
48 document.writeln( "<br />global variable x is " +
49 x + " on exiting functionB" + "</p>" );
50 }
51 // -->
52 </script>
53
54 </head>
55 <body onload = "start()"></body>
56 </html>
Function functionB multiplies the value of x by 10.
47. 2004 Prentice Hall, Inc. All rights reserved.
47
10.8 Scope Rules
Fig. 10.8 Scoping example.
48. 2004 Prentice Hall, Inc. All rights reserved.
48
10.9 JavaScript Global Functions
• Global object
– Always available
– Provides 7 methods
– Do not need to explicitly reference Global before method
call
– Also holds all global variables, user defined functions
49. 2004 Prentice Hall, Inc. All rights reserved.
49
10.9 JavaScript Global Functions
Global function Description
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 D, ASCII
Character Set) are encoded in a hexadecimal format
(see Appendix E, Number Systems) 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, it 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.9 JavaScript global functions.
50. 2004 Prentice Hall, Inc. All rights reserved.
50
10.9 JavaScript Global Functions
Global function Description
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 Appendex E, Number
Systems, for more information on binary, octal and
hexadecimal numbers.
unescape This function takes a string as its argument and
returns a string in which all characters previously
encoded with escape are decoded.
Fig. 10.9 JavaScript global functions.
51. 2004 Prentice Hall, Inc. All rights reserved.
51
10.10 Recursion
• Recursive functions
– Call themselves
• Recursion step or recursive call
• Part of return statement
– Must have base case
• Simplest case of problem
• Returns value rather than calling itself
– Each recursive call simplifies input
• When simplified to base case, functions return
52. 2004 Prentice Hall, Inc. All rights reserved.
52
10.10 Recursion
• Factorials
– Product of calculation n · (n - 1) · (n - 2) · … · 1
– Iterative approach:
var factorial = 1;
for ( var counter = number; counter >= 1; --counter )
factorial *= counter;
– Note each factor is one less than previous factor
• Stops at 1: base case
• Perfect candidate for recursive solution
53. 2004 Prentice Hall, Inc. All rights reserved.
53
10.10 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
Fig. 10.10 Recursive evaluation of 5!.
Final value = 120
54. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
54
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.11: FactorialTest.html -->
6 <!-- Recursive factorial example -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Recursive Factorial Function</title>
11
12 <script language = "javascript">
13 document.writeln( "<h1>Factorials of 1 to 10</h1>" );
14 document.writeln(
15 "<table border = '1' width = '100%'>" );
16
17 for ( var i = 0; i <= 10; i++ )
18 document.writeln( "<tr><td>" + i + "!</td><td>" +
19 factorial( i ) + "</td></tr>" );
20
21 document.writeln( "</table>" );
22
FactorialTest.html
(1 of 2)
Calling function factorial and passing
it the value of i.
55. 2004 Prentice Hall, Inc.
All rights reserved.
Outline
55
23 // Recursive definition of function factorial
24 function factorial( number )
25 {
26 if ( number <= 1 ) // base case
27 return 1;
28 else
29 return number * factorial( number - 1 );
30 }
31 </script>
32 </head><body></body>
33 </html>
FactorialTest.html
(2 of 2)
Variable number gets the value of variable i.
Call to function factorial and passing it 1
less than the current value of number .
56. 2004 Prentice Hall, Inc. All rights reserved.
56
10.10 Recursion
Fig. 10.11 Factorial calculation with a recursive function.
57. 2004 Prentice Hall, Inc. All rights reserved.
57
10.11 Recursion vs. Iteration
• Iteration
– Explicitly uses repetition structures to achieve result
– Terminates when loop-continuation condition fails
– Often faster than recursion
• Recursion
– Repeats through function calls
– Terminates when base case reached
– Slower due to function call overhead
• Each call generates new copy of local variables
– Easy to read and debug when modeling problem with
naturally recursive solution
58. 2004 Prentice Hall, Inc. All rights reserved.
58
10.11 Recursion vs. Iteration
Chapter Recursion examples and exercises
10 Factorial function
Sum of two integers
Multiply two integers
Raising an integer to an integer power
Visualizing recursion
12 Printing a string input at the keyboard backward
13 Navigating the object hierarchy in Dynamic HTML
Fig. 10.12 Recursion examples and exercises in the text.