Functions and Data Structures Week 4 INFM 603. Programming in Four Parts Structured Programming  Data Structures  Modular Programming Object-Oriented.

Slides:



Advertisements
Similar presentations
Computer and Communication Fundamental Basic web programming Lecture 8 Rina Zviel-Girshin.
Advertisements

Chapter 6: JavaScript Functions 6.1 The Purpose of Functions 6.2 Defining JavaScript Functions 6.3 Using JavaScript Functions 6.4 Global Functions and.
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
The Web Warrior Guide to Web Design Technologies
Web Infrastructure Week 3 INFM 603. The Key Ideas Questions Structured Programming Modular Programming Data Structures Object-Oriented Programming.
LBSC 690 Session #10 Programming, JavaScript Jimmy Lin The iSchool University of Maryland Wednesday, November 5, 2008 This work is licensed under a Creative.
Data Structures Week 4 INFM 603. The Key Ideas Structured Programming  Modular Programming  Data Structures Object-Oriented Programming.
Computing Concepts Advanced HTML: Tables and Forms.
Programming Week 5 LBSC 690 Information Technology.
Information Technology Center Hany Abdelwahab Computer Specialist.
CIS101 Introduction to Computing Week 10 Spring 2004.
LBSC 690: Session 10 Programming, JavaScript Jimmy Lin College of Information Studies University of Maryland Monday, November 12, 2007.
29 November JavaScript: Arrays and Iterations Functions.
Computer Science 103 Chapter 4 Advanced JavaScript.
CIS101 Introduction to Computing Week 10. Agenda Your questions Final exam and final project CIS101 Student Survey Class presentations: Your Mad Libs.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
CSS, Programming Intro Week 4 INFM 603. Agenda JavaScript Intro.
Advanced Decisions and Loops Chapter Some Simple Schoolroom Statistics.
CST JavaScript Validating Form Data with JavaScript.
1 JavaScript: Functions and Arrays October 18, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Objects and Events Week 5 INFM 603. Muddiest Points Commonly used functions.getElementById Recursion Hashing.
JavaScript Form Validation
JS: DOM Form Form Object Form Object –The Form object represents an HTML form. –For each instance of a tag in an HTML document, a Form object is created.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
Structured Programming Week 3 INFM 603. Muddiest Points Emergent behavior of the Web HTML class attribute The details of JavaScript … p.style1 { font-family:arial;
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Arrays – What is it? – Creation – Changing the contents Functions – What is it? – Syntax – How they work – Anonymous functions A quick lesson in Objects.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
1 Introduction to Javascript Peter Atkinson. 2 Objectives To understand and use appropriately some of the basic elements of Javascript: –alert and prompt.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
CS0004: Introduction to Programming Variables – Strings.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
CHAPTER 4 Java Script อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
Topic: An Introduction to JavaScript - from Beginning JavaScript by Wilton (WROX)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
CO1552 Web Application Development HTML Forms, Events and an introduction to JavaScript.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
 Agenda 2/20/13 o Review quiz, answer questions o Review database design exercises from 2/13 o Create relationships through “Lookup tables” o Discuss.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
JavaScript III Functions and Abstraction. 2 JavaScript so far statements assignment function calls data types numeric string boolean expressions variables.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
JavaScript, Fourth Edition
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Making dynamic pages with javascript Lecture 1. Java script java versus javascript Javascript is a scripting language that will allow you to add real.
JavaScript II ECT 270 Robin Burke. Outline Functions Events and event handling Form validation.
Tutorial 11 1 JavaScript Operators and Expressions.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript arrays.
5 th and 4 th ed: Chapters 9, 10, 11 SY306 Web and Databases for Cyber Operations SlideSet #7: JavaScript Functions and Arrays.
JavaScript and Ajax (JavaScript Functions) Week 5 Web site:
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Chapter 5 Validating Form Data with JavaScript
Chapter 11 - JavaScript: Arrays
HTML & teh internets.
JavaScript.
JavaScript: Functions
JavaScript: Functions.
Web Programming and Design
Intro to Programming (in JavaScript)
Presentation transcript:

Functions and Data Structures Week 4 INFM 603

Programming in Four Parts Structured Programming  Data Structures  Modular Programming Object-Oriented Programming

Arrays A set of elements –For example, the number of days in each month Each element is assigned an index –A number used to refer to that element For example, x[4] is the fifth element (count from zero!) –Arrays and iteration work naturally together “Constructor” allocates space –var myArray = new Array(5); // all unitialized –var myArray = [42, 17,, 22, 1]; // partially initialized

Indexing Values expenses [0]= “25”; expenses[1] = “30”; … expenses[365] =“100”; OR var expenses = [“25”,”30”,…”100”]; var expenses = new Array (“25”,”30”,…”100”); Index always starts at

Array Example // allocate five-element Array (indexed 0..4) var n = new Array(5); // assign values to each element of Array n for (var i=0; i<n.length; i++) { n[i] = i; } // output index and value of each element for (var i=0; i<n.length; i++) { document.writeln(i + “: “ + n[i]); }

Data Structures Constant –Names given to unchanging values (for readability) Scalar –Single-valued item (int, float, boolean) Object –Multi-valued item, mixed data types [+methods] Array –Integer-indexed set of objects (usually of one type) Associative array (“hash table”) –Object-index set of objects (usually of one type)

Associative Arrays in JavaScript var myArray = new Array(); myArray[‘Monday'] = 1; myArray[‘Tuesday'] = 2; myArray[‘Wednesday'] = 3; // show the values stored for (var i in myArray) { // skips unitialized alert('key is: ' + i + ', value is: ' + myArray[i]); }

Common Uses of Arrays Iterative computation Queue (FIFO) Stack (LIFO)

Hands On Write a JavaScript program that asks you for three numbers and outputs the last one Use arrays instead of three different variables

var numbers = new Array(); var c,input; for (c=0;c<3;c++) { input = prompt(“Type a number"); numbers[c] = input; } document.writeln("The last number is" + numbers[2]);

Array Methods array.join() – Put together all elements as a string array.sort() – Order alphabetically array.reverse() – Reverse order of array array1.concat(array2,array3,…) – Concatenates two or more arrays

Functions Reusable code for complex code blocks –Takes zero or more values as “parameters” –Returns at most one value as the “result” function convertToCelsius(f) { var celsius = 5/9 * (f-32); return celsius; } c = convertToCelsius(fh); function convertToCelsius(f) { var celsius = 5/9 * (f-32); return celsius; } var fh = 60; c = convertToCelsius(fh);

More Examples var r = weirdAddition(2, 4); var a = 2; var b = 3; var s = weirdAddition(a, b); function weirdAddition(a, b) { var result = a + b - 0.5; return result; }

Writing JavaScript Functions Convenient to put in the section –Use to prevent display of code … <!-- function calculate() { var num = eval(document.input.number.value); … document.output.number.value = total; } //--> …

Uses of Functions Compactness –Minimizing duplicative code Modular programming –Abstraction –Reusability –Avoid “side effects”

Function Format function Name(parameter1, parameter2,…) { statements }

Example JavaScript Program Template /*ask for user input*/ var day = prompt("Enter day"); var kind = prompt("Enter kind"); /*call function*/ menu(day, kind); /* Function definition */ function menu(day, kind) { var actualChoices; if (day === "Monday" || kind === "healthy") { actualChoices = " chicken "; } else { actualChoices = " steak, cheesecake, whip cream, lard "; } document.writeln("The " + kind + " Menu for " + day + " "); document.writeln(actualChoices); }

Parameter Passing Scalars are copied –“Pass by value” Arrays (and all objects) pass “by reference” –The values in the array are not copied Be careful to make “side effects” explicit –No need to return the same reference Functions can also be passed as parameters –Unchangable, so “by reference” = “by value” Returned values work the same way

Returning a Function’s Result function Name(parameter1, parameter2,…) { statements; return value; }

Functions /* calling main */ main(); function main() { /* Where we call the other functions */ var firstValue = Number(prompt("First Value")); var secondValue = Number(prompt("Second Value")); var max; max = maxValue(firstValue, secondValue); alert("Maximum value is: " + max); } function maxValue(value1, value2) { var maximum; if (value1 > value2) { maximum = value1; } else { maximum = value2; } return maximum; // what happens if we don't return a value? }

Hands On Write a JavaScript function that asks for two names and returns the one with the shortest length

/* calling main */ var firstName = prompt("First Name"); var secondName = prompt("Second Name"); var max; max = maxValue(firstValue, secondValue); alert("Longest string is: " + max); function maxValue(value1, value2) { var maximum; if (value1.length > value2.length) { maximum = value1; } else { maximum = value2; } return maximum; // what happens if we don't return a value? }

Scope of a Variable In JavaScript, var “declares” a variable var mystery;create a variable without defining its type var b = true;create a boolean b and set it to true var n = 1;create an integer n and set it to 1 var s = “hello”;create a string s and set it to “hello” Variables declared in a function are “local” Function parameters are implicitly declared (local) Same name outside function refers to different variable All other variables are “global”

Global vs Local Variables Pass by value /* calling main */ main(); var m = 10, t = 20; document.writeln("Before m value is: " + m + ", t value is: " + t + " "); wrongSwap(m, t); document.writeln("After m value is: " + m + ", t value is: " + t); /* What is wrong with this function? */ function wrongSwap(x, y) { var temp = x; x = y; y = temp; } What does this program do? Try it!

Modify Global Variables var m = 10, t = 20; document.writeln("Before m value is: " + m + ", t value is: " + t + " "); wrongSwap(m, t); document.writeln("After m value is: " + m + ", t value is: " + t); /* What is wrong with this function? */ function wrongSwap(x, y) { var temp = x; var temp2 = y; m = temp2; t = temp; }

Sequential Search Source: Wikipedia

Binary Search Source: Wikipedia

Recursion Source: Wikipedia

Recursion A function can call itself –Local variables are different each time Every invocation of the function must end –There must be a path that ends the recursion –That path must eventually be taken –The usual way to do this is an initial if statement Never essential –But sometimes more elegant than iteration

Binary Search with Recursion function binarySearch(theArray, key, low, high) { var middle; if (low>=high) { // Safety check! if (key==theArray[low]) { return low; } else { return -1; } } else { middle = Math.floor((low+high)/2); // Explicit! buildOutput( theArray, low, middle, high ); if (key<=theArray[middle]) { // Equality! return binarySearch(theArray, key, low, middle); } else { return binarySearch(theArray, key, middle+1, high); }

Some Math Functions Math.abs() – Absolute value –Example: Math.abs(-10) Math.max() – Maximum of two values –Example: Math.max(10, 20) Math.sqrt() – Square root –Example: Math.sqrt(4) Math.random() – Random value between 0 and less than 1 –Example: Math.random() Constants –Math.PI – Mathematical constant pi

One More Example Write a JavaScript program that asks for a number (n) and writes an HTML table with two columns: –Column1: numbers 0 to n –Column2: square root of number For n=4

Square Root Table var currValue = 0; var maximumValue; maximumValue = Number(prompt("Enter maximum value")); document.writeln(" "); document.writeln(" Table "); document.writeln(" Number 2*Number "); while (currValue <= maximumValue) { document.writeln(" " + currValue + " " + currValue*2 +" "); currValue = currValue + 1; } document.writeln(" ");

Documentation Tips Reflect your pseudocode in your code –Use meaningful variable names –Use functions for abstractable concepts And name those functions well –Use comments to fill remaining gaps Add a comment to identify each revision –Give author, date, nature of the change Waste space effectively –Use indentation and blank lines to guide the eye

Using JavaScript with Forms HTML: Please enter a number: The sum of all numbers up to the number above is JavaScript: var num = eval(document.input.number.value); document.output.number.value = 10; Reads in a value from the first form (eval method turns it into a number) Changes the value in the second form

HTML Form Element Types Textarea (multiple lines) Input –Text (single line) –Password (like text, but masked) –Hidden (like text, but not displayed at all) –Button –Checkbox (multiple selection) –Radio (single selection) Select (dropdown list) see for examples

Linking Forms to Functions Events: –Actions that users perform An “event handler” is triggered by an event –onClick: the user clicked on the item –onMouseover: the mouse moved onto the item –onMouseout: the mouse moved off of the item

Referring to Form Content Enter integer search key … var inputVal = document.getElementById("inputVal"); var searchKey = inputVal.value; Please enter your age … var age = document.years.box.value;

Looking Ahead Objects Events

Events allow an HTML webpage to react to a users’ behavior (event handler) – Click of a mouse – Mouse over an element – User strokes a key – Image has been loaded – Input field is changed (forms)

More complex events…Forms Click on button to select an action Text box for entering a line of text Radio buttons for making one selection among a group of options Check boxes for selecting or deselecting a single, independent option Lists of things to select one

Push Button

Text Box This is a text area.

Radio Button Apples Oranges

Check Box I have a bike I have a car

List Oranges Apples Lemons Bananas

Handling Events…JavaScript! JavaScript is responsible for “doing things” when buttons are clicked <input type="button" value="This is a button" onclick="myFunction()">

Handling Events…JavaScript! <input type="button" value="This is a button" onclick="myJSFunction()"> function myJSFunction() { do something}

Example with Push Button function myJSFunction() { document.getElementById("demo").innerHTML="Hello World"; } Try this

Text Box: access text var textInput = document.getElementById("textInput"); var textValue = textInput.value; alert(textValue);

Text Box <body Forms function handleClick() { var textInput = document.getElementById("textInput"); USE THE DOM var textValue = textInput.value; alert("The input text is: " + textValue); }

Radio Button One Two var onechecked = document.getElementById("radioone").checked; alert(“button one checked: " + onechecked);

<body Forms function handleClick() { var onechecked = document.getElementById("radioone").checked; var twochecked = document.getElementById("radiotwo").checked; alert("one checked: " + onechecked+" two checked "+twochecked); } One Two

Check Box I have a dog var hasDog = document.getElementById("checkDog").checked;

<body Forms function handleClick() { var hasDog = document.getElementById("checkDog").checked; var hasCat = document.getElementById("checkCat").checked; alert("dog? " + hasDog+ " cat? " + hasCat); } I have a dog I have a cat

List Oranges var selectInput = document.getElementById("selectInput"); var selectedIndex = selectInput.selectedIndex; var selectedValue = selectInput.options[selectedIndex].value;

<body Forms function handleClick() { var selectInput = document.getElementById("selectInput"); var selectedIndex = selectInput.selectedIndex; var selectedValue = selectInput.options[selectedIndex].value; alert("Which fruit do you prefer? " + selectedValue); } Oranges Lemons Apples Bananas

Before You Go On a sheet of paper, answer the following (ungraded) question (no names, please): What was the muddiest point in today’s class?