Computers and Scientific Thinking David Reed, Creighton University Functions, Randomness and Libraries 1.

Slides:



Advertisements
Similar presentations
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Advertisements

Introducing JavaScript
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
1 CSC 121 Computers and Scientific Thinking David Reed Creighton University Chapter 9 Abstraction and User-Defined Functions.
1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
The Web Warrior Guide to Web Design Technologies
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Introduction to C Programming
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
CS 201 Functions Debzani Deb.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
Introduction to C Programming
Computers and Scientific Thinking David Reed, Creighton University Functions and Randomness 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.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Computers and Scientific Thinking David Reed, Creighton University JavaScript and User Interaction 1.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Introduction to JavaScript Basharat Mahmood, Department of Computer Science, CIIT, Islamabad, Pakistan. 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
1 Functions Lecfture Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
Computers and Scientific Thinking David Reed, Creighton University Functions and Libraries 1.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
1 CSC 121 Computers and Scientific Thinking David Reed Creighton University JavaScript and Dynamic Web Pages.
CSC 121 Computers and Scientific Thinking David Reed Creighton University 1 Abstraction and User-Defined Functions.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript.
JavaScript, Fourth Edition
Understanding JavaScript and Coding Essentials Lesson 8.
Tutorial 11 1 JavaScript Operators and Expressions.
CSC 121 Computers and Scientific Thinking Fall Interactive Web Pages.
JavaScript and Ajax (JavaScript Functions) Week 5 Web site:
CSC 121 Computers and Scientific Thinking Fall Event-Driven Programming.
JavaScript 101 Lesson 6: Introduction to Functions.
1 CSC 121 Computers and Scientific Thinking David Reed Creighton University JavaScript and Dynamic Web Pages.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
JavaScript: Functions
JavaScript: Functions.
Chapter 10 - JavaScript: Functions
Chapter 5 - Functions Outline 5.1 Introduction
Event Driven Programming & User Defined Functions
T. Jumana Abu Shmais – AOU - Riyadh
Abstraction and User-Defined Functions
Chapter 7 Event-Driven Pages
Classes, Objects and Methods
Chapter 11 Conditional Execution
Chapter 9 Abstraction and User-Defined Functions
Chapter 17 JavaScript Arrays
Chapter 7 Abstraction and User-Defined Functions
Computers and Scientific Thinking David Reed, Creighton University
Chapter 5 JavaScript Numbers and Expressions
Presentation transcript:

Computers and Scientific Thinking David Reed, Creighton University Functions, Randomness and Libraries 1

Predefined Functions in addition to parseFloat, JavaScript has numerous predefined mathematical functions the functest.html page allows you to explore these 2 recall: in mathematics, a function is a mapping from inputs to a single output e.g., the absolute value function: |-5|  5, |17.3|  17.3 in JavaScript, a function is applied to inputs via a function call specify the function name, followed by inputs in parentheses num = parseFloat(document.getElementById('numBox').value);

Math Functions 3 Math.sqrtdetermines the square root Math.sqrt(9)  √9 = 3 Math.sqrt(12.25)  √12.25 = 3.5 Math.maxdetermines the maximum of two values Math.max(12, 8.5)  12 Math.max(-3, -8)  -3 Math.pow raises a number to a power Math.pow(2, 10)  2 10 = 1024 Math.pow(2, -1)  2 -1 = 0.5 Math.pow(9, 0.5)  = 3 Math.min, Math.abs, Math.round, Math.ceil, Math.floor, …

Rounding Page 4 uses the Math.round function to round a number to 1 digit Math.round( *10)/10  Math.round( )/10  31/10  3.1

Math.random a call to Math.random can be placed in an expression to affect the range 2*Math.random()  [0…2) Math.random() + 1  [1…2) 9*Math.random() + 1  [1…10) Math.floor(9*Math.random() + 1)  1, 2, 3, …, 9 5 Math.random generates a pseudo-random number in the range [0…1) pseudo-random refers to the fact that the numbers appear randomly distributed, but are in fact generated by a complex algorithm note: this function has no inputs; it returns a different number each call Math.random()  Math.random()  Math.random() 

Lucky Number Page displays a random number from the range specified by the text boxes 6

Simplifying buttons functions provide a mechanism for simplifying complex buttons such as this recall: functions minimize the amount of detail that has to be considered  e.g., can use Math.sqrt without worrying about how it works functions reduce the length and complexity of code  e.g., a single call to Math.sqrt replaces the underlying complex algorithm 7 consider the button from lucky1.html : the size of ONCLICK attribute makes the button complex and difficult to read plus, must be careful with nested quotes ("…" vs. '…')

Simple user-defined functions in addition to JavaScript's predefined functions, the user can define new functions in the HEAD section and call them within the page we will explore user-defined functions fully in Chapter 9 for now, the following simple form suffices for simplifying buttons 8 a function definition begins with the word function followed by its name and ()  a function name should be descriptive of the task being performed lines beginning with // are comments that describe the function's behavior  comments are ignored by the interpreter, but make code more user-readable the statements to be executed when the function is called are placed between the curly braces

Lucky Number Revisited the code from the button is moved to the user- defined GenerateNumber function SCRIPT tags enclose the function definition in the HEAD as a result, the button is greatly simplified GENERAL ADVICE: if more than one statement is to be associated with a button, define a separate function 9

Example: Dice Simulation suppose we wanted to simulate the roll of a 6-sided die at the click of a button, see a randomly selected roll of a die 10 can use Math.random and Math.floor to generate a random roll between 1 & 6 roll = Math.floor(Math.random()*6) + 1; die images are stored as …,

Example: Dice Simulation the desired die image can be selected using the roll variable '…/die' + roll + '.gif' 11

Example: Slide Show the dice simulation page can be generalized into a random slide show name the slide images using a consistent naming scheme slide1.jpg, slide2.jpg, slide3.jpg, … each time the button is clicked, the SelectImage function is called to randomly change the image to select a random slide at the start, make use of the ONLOAD attribute of the BODY tag here, call SelectImage after the page loads in order to start with a random image 12

Example: Banner Ads 13 the random slide show page can be generalized into random banner ads name the ad images using a consistent naming scheme ad0.jpg, ad1.jpg, ad2.jpg, … the SelectAd function changes the ad to a random image instead of calling the function at the click of a button, can automate using the predefined setInterval function setInterval('JAVASCRIPT_FUNCTION_CALL', INTERVAL_IN_MSEC) sets a timer and repeatedly executes the specified function at set intervals will call the function to change the ad image every half second

Example: Banner Ads 14

Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly confronted with complexity we don't necessarily know how it works, but we know how to use it e.g., how does a TV work? a car? a computer? 15 we survive in the face of complexity by abstracting away details to use a TV/car/computer, it's not important to understand the inner workings we ignore unimportant details and focus on those features relevant to using it e.g., TV has power switch, volume control, channel changer, … JavaScript functions (like Math.sqrt ) provide computational abstraction a function encapsulates some computation & hides the details from the user the user only needs to know how to call the function, not how it works Chapter 7 introduced simple user-defined functions  could encapsulate the statements associated with a button, call the function as needed

General Function Form to write general-purpose functions, we can extend definitions to include: 1) parameters, 2) local variables, and 3) return statements parameters are variables that correspond to the function’s inputs (if any)  parameters appear in the parentheses, separated by commas local variables are temporary variables that are limited to that function only  if require some temporary storage in performing calculations, then declare local variables using the keyword var, separated by commas  a local variable exists only while the function executes, so no potential conflicts with other functions a return statement is a statement that specifies an output value  consists of the keyword return followed by a variable or expression 16

Declaring Local Variables we have seen that variables are useful for storing intermediate steps in a complex computation within a user-defined function, the programmer is free to create new variables and use them in specifying the function’s computation however, by default, new variables used in a function are global (i.e., exist and are accessible anywhere in the page)  but what if the same variable name is already used elsewhere? 17 to avoid name conflicts, the programmer should declare temporary variables to be local a variable declaration is a statement that lists all local variables to be used in a function (usually the first statement in a function) general form: var LOCAL_1, LOCAL_2,..., LOCAL_n;

ESP Test Page consider a simple ESP test 1. user thinks of a number between clicks on the button to see the computer's pick 18 number is declared local to pickNumber only exists while the function executes

Functions with Inputs most of the predefined function we have considered expect at least one input e.g., Math.sqrt takes a number as input, and returns its square root as output Math.sqrt(9)  3 e.g., Math.max takes two numbers as inputs, and returns the maximum as output Math.max(7, 3)  7 in English, the word parameter refers to some aspect of a system that can be varied in order to control its behavior in JavaScript, a parameter is a variable (declared inside the function's parentheses) whose value is automatically initialized to the corresponding input value when the function is called parameters allow the same function to perform different (but related) tasks when called with different input values 19

ESP Test Page Revisited 20 better design: have a button for each guess to guess 1, the user clicks the ' Guess 1' button instead of 4 different functions (that behave similarly), have 1 function with a parameter the number corresponding to the guess is passed in as an input, displayed as the guess

Multiple Inputs if a function has more than one input, parameters in the function definition are separated by commas input values in the function call are separated by commas values are matched to parameters by order 1 st input value in the function call is assigned to the 1 st parameter in the function 2 nd input value in the function call is assigned to the 2 nd parameter in the function <input type="button" value="Cow Verse" onclick="OldMacVerse('cow', 'moo');">

Parameters and Locals parameters play an important role in functions they facilitate the creation of generalized computations i.e., the function defines a formula, but certain values within the formula can differ each time the function is called parameters are special instances of local variables when the function is called, memory cells are allocated for the parameters and each input from the call is assigned to its corresponding parameter once a parameter has been assigned a value, you can refer to that parameter within the function just as you would any other variable when the function terminates, the parameters “go away,” and their associated memory cells are freed parameters are declared and initialized automatically do not declare them as local variables 22

Functions with Return displaying results using an INNERHTML assignment or alert is OK for some functions for full generality, we need to be able to return an output value, which can then be used in other computations e.g., number = Math.sqrt(9); cm = InchesToCentimeters(in); 23 a return statement can be added to a function to specify its output value when the return statement is reached, the variable or expression is evaluated and its value is returned as the function's output general form: return OUTPUT_VALUE;

Function Libraries functions such as InchesToCentimeters can be added to the HEAD of a page tedious if the function is to be used in many pages involves creating lots of copies that all must be maintained for consistency the alternative for general purpose functions is to place them in a library file a library file is a separate text file that contains the definitions of one or more JavaScript functions it can be loaded into any page by adding an HTML element to the HEAD 24 advantages of library files: avoids duplication (only one copy of the function definition) makes it easy to reuse functions (simply load the library file into any page) makes it easy to modify functions (a single change to the library file automatically affects all pages that load the library

Conversion Page 25 the convert.js library file is loaded into the page this makes the InchesToCentimeters function accessible within the page since ConvertToCm is specific to this page, it directly in the HEAD (as opposed to a library file)

random.js Library the random.js library contains useful functions for generating random values 26 any page can utilize the functions by first loading the random.js library for example, could revise the ESP Test page to use RandomInt : number = RandomInt(1, 4);

Errors to Avoid When beginning programmers attempt to load a JavaScript code library, errors of two types commonly occur: 1. if the SCRIPT tags are malformed or the name/address of the library is incorrect, the library will fail to load  this will not cause an error in itself, but any subsequent attempt to call a function from the library will produce Error: Object Expected (using Internet Explorer) or Error: XXX is not a function (using Firefox), where XXX is the entered name 2. when you use the SRC attribute in a pair of SCRIPT tags to load a code library, you cannot place additional JavaScript code between the tags  think of the SRC attribute as causing the contents of the library to be inserted between the tags, overwriting any other code that was erroneously placed there ANYTHING PLACED IN HERE WILL BE IGNORED  if you want additional JavaScript code or another library, you must use another pair of SCRIPT tags 27

Designing Functions functions do not add any computational power to the language a function definition simply encapsulates other statements still, the capacity to define and use functions is key to solving complex problems, as well as to developing reusable code encapsulating repetitive tasks can shorten and simplify code functions provide units of computational abstraction – user can ignore details functions are self-contained, so can easily be reused in different applications 28 when is it worthwhile to define a function? if a particular computation is complex—meaning that it requires extra variables and/or multiple lines to define if you have to perform a particular computation repeatedly when defining a function, you must identify the inputs the computation to be performed using those inputs the output

Design Example consider the task of designing an online Magic 8-ball  (Mattell, Inc.) must be able to ask a yes/no type question receive an answer (presumably, at random) 29 could use:  a text box for entering the question  a DIV element for displaying the answer  a clickable image for initiating the action – which involves calling a function to process the question, select an answer, and display it in the DIV