Presentation is loading. Please wait.

Presentation is loading. Please wait.

M150: Data, Computing and information

Similar presentations


Presentation on theme: "M150: Data, Computing and information"— Presentation transcript:

1 M150: Data, Computing and information
Outline Unit eight What’s next. Review questions. Your questions.

2 1- Unit eight :Programs and Data
Arrays as a collection of data Functions as tasks and subtasks in a program Events and Event Handlers in GUI interfaces String processing and functions

3 1- Unit eight: Structured data - Array
There are many situations where we want to deal with collections of data values that are related to each other in some way. In processing such collections of data values, we will often want to treat each value in a collection in a similar way. In such situations we talk about structured data. In most programming languages the name given to a collection of data values, that are all of the same type, e.g. numeric values or all string values, is an array. 3

4 1- Unit eight: Arrays An array is a data structure that consists of a list of data values of the same type; for example, numbers or Strings. An array should have a name. Each data value is called an element. The position of the data element in the array is called the index or subscript. Index of an array starts at 0.

5 1- Unit eight: Arrays Arrays in JavaScript
Each element referenced by a number Start at “zeroth element” Subscript or index Accessing a specific element Name of array Brackets Number of element Arrays know their length length property

6 1- Unit eight: Array Declaration & Allocation
var rainArray = [111, 115, 200, 95, 23, 59, 144, 66, 37] JavaScript interpreter recognizes this is an array because of the square brackets. var rainArray = new Array(12) Reserved word new is used to create an Array object. The number 12 will provide enough memory for the 12 elements that are going to be stored in it. Initial value for the elements of the array is undefined. (See Fig 2.3)

7 1- Unit eight: Array structure
rainArray rainArray[ 0 ] 111 rainArray[ 1 ] 115 rainArray[ 2 ] 200 rainArray[ 3 ] 95 rainArray[ 4 ] 23 59 rainArray[ 5 ] rainArray[ 6 ] 68 rainArray[ 7 ] 33 rainArray[ 8 ] 39 rainArray[ 9 ] 144 Position number (index or subscript) of the rainArray[ 10 ] 66 element within rainArray rainArray[ 11 ] 37

8 1- Unit eight: Accessing Array Elements
Accessing individual elements of an array myM150MarkArray[1] = 95 document.write(‘My Mark for TMA02 was ‘ + myM150MarkArray[1] );

9 1- Unit eight: Array length
JavaScript Array objects have a length property, which indicates the number of elements in the array. To find the length of an array named myArray, we use myArray.length. It is important to remember that the length of an array is one greater than the index value of its last element. 9

10 1- Unit eight: Algorithm
An algorithm is a clearly specified set of instructions to be followed in order to carry out a task or obtain a solution to a problem. Instructions written in an algorithm are known as structured English Example of an algorithm to output all elements of an array For each month of the year Write out the rainfall figure for that month End for

11 1- Unit eight: Coding an algorithm
JavaScript Code for previous algorithm Example Declare a variable as a loop counter. Specify a starting value. Formulate the condition for iterating round the loop. month < rainArray.length. Finally, state the rule for incrementing the loop counter. month = month+1. For (var month =0; month < rainArray.length; month = month+ 1) { Document.write(rainArray[month] + ‘<BR>’) }

12 1- Unit eight : Arrays Entering data values into an array
Translate the following into code: For each month of the year prompt for the rainfall figure for that month and put it into the correct position in the array end for. var rainArray = new Array(12); for (var month =0; month < rainArray.length; month = month + 1) { rainArray[month] = window.prompt(‘Enter rainfall value’,’’) }

13 1- Unit eight : Max value of an Array
Algorithm: Initialize maximum monthly rainfall to rainfall in first month of the year For each month of the year (except the first) Compare the month’s rainfall with the current maximum If it is bigger replace the current maximum with this month’s value End for Write out the final maximum value

14 1- Unit eight : Max value of an Array
JavaScript Code: MaxMonthlyRainfall = rainArray[0]; For (var month =1; month < rainArray.length; month = month + 1) { If (rainArray[month] > maxMonthlyRainfall) maxMonthlyRainfall = rainArray[month] } }; Document.write (‘Maximum monthly rainfall = ’ + maxMonthlyRainfall);

15 1- Unit eight: Parallel Arrays and Math object
Using Parallel Arrays: We say that two arrays are parallel when the information held at the same index in two or more arrays is related. SAQ Program to convert rainfall data from millimeters to inches. Managing the precision of numeric output: use Math object Math.round Math.round(2.4) evaluates to 2. Math.round(2.7) evaluates to 3.

16 1- Unit eight: Functions
In real life, programs are often very large and have separate subtasks to perform. We need to organize these subtasks. Function is a way to handle and organize these subtasks.

17 1- Unit eight: Functions
One big task may be broken into simpler subtasks. A program is a main task that can be broken down into a collection of subtasks. JavaScript provides functions as a way for handling subtasks. i.e. parseFloat().

18 1- Unit eight: Functions
Examples of functions are: drawBox() drawColouredBox() drawColouredBox(‘blue’) drawSizedBox(6,10) calculateArea(10, 8) document.write(‘The area of the box is ‘ + calculateArea (6,10) + ‘<BR>’)

19 1- Unit eight: Functions
Writing functions in JavaScript A function is composed of 2 main parts: header and body. Header contains the reserved word function. After the function keyword, we have the function name. After the name, a list of the arguments/parameters is enclosed in parentheses. If no argument is needed, the list is empty. The body contains the statements that carry out the work of the function. When we use a function in a program, we say that we invoke or call the function.

20 1- Unit eight: Functions
General form of a function: function FUNCTION_NAME(PARAMETER_1, PARAMETER_2,..., PARAMETER_n) // Assumes: DESCRIPTION OF ASSUMPTIONS MADE ABOUT PARAMETERS // Returns: DESCRIPTION OF VALUE RETURNED BY FUNCTION { STATEMENTS_TO_PERFORM_(AND_RETURN)_THE DESIRED_COMPUTATION; }

21 1- Unit eight: Functions Example
Function doThis() { document.write(‘do this’ + ‘<BR>’) } function call: doThis();

22 1- Unit eight: Functions
Functions with Arguments Function doThis(aTime) { document.write(‘do this ‘ + aTime + ‘<BR>’) } Function call: doThis(‘now’)

23 1- Unit eight: Functions
Functions which return a value vs procedural functions In JavaScript, a function is not required to have a return statement. If no return, the function automatically returns the special value: undefined: we call these procedural functions. Thus, a JavaScript function has an output whether you specify it or not. An example of a function that returns a value. function toInches(numberOfMm) { return numberOfMm * }

24 1- Unit eight: Functions
Functions to tidy up numeric arguments. function twoDPs(anyNumber) { return Math.round(100 * anyNumber)/100 } Other examples of predefined functions for Math object: Math.abs (number) Math.random() Math.sqrt(number)

25 1- Unit eight: Function calling another function
25

26 1- Unit eight: Functions with more than one argument
Problem: write a function printCharacterBlock that takes 3 arguments: number of lines, number of characters, and the output character. Algorithm: for each line from 1 to number of lines for each position from 1 to number of characters write the given character end for move to a new line End for

27 1- Unit eight: Functions with more than one argument
Code: function printCharacterBlock (lines, number, outputCharacter) { for ( var line = 1; line <=lines; line = line + 1) for( var position = 1; position <= number; position = position + 1) document.write(outputCharacter) }

28 1- Unit eight: Functions with more than one argument
Output: 28

29 1- Unit eight: Functions
Hints for writing functions Why write a function To carry out a specific task Code reuse How to design a function Do we need arguments? Does it return a value? Any already defined functions that can help do the job or part of it? Have we chosen meaningful names?

30 1- Unit eight : Graphical User Interface
The introduction of Graphical User Interface or GUI marks the most significant move forward in computer usability. It has transformed our interaction with PCs from command-line interface to a GUI interface. In a GUI interface, there are various visual components on the screen with which we can interact in a more intuitive manner.

31 1- Unit eight : Events An event-driven model is a model in which the computer registers the occurrence of an event whenever the user does something on the screen. For example, an event might be a click on a button, or the movement of the cursor over an image. Programmers have to provide a piece of code for every event. 31

32 1- Unit eight : Events These pieces of code are called event handlers.
Each event handler needs to be attached in some way to the component for which the event occurred. In general GUI programming consists of a relatively large number of relatively small pieces of code. 32

33 1- Unit eight : Adding GUI components to programs
A form can have a number of GUI widgets (such as buttons and text boxes). GUI elements must be associated with a form, next we will show the procedure steps for using them. 33

34 1- Unit eight : Adding GUI components to programs
Create a form on which you can place the elements, by including the <FORM> and </FORM> tags. Assign a value to the NAME attribute of the form. Create each element which receives input from a user (such as a button), using the <INPUT> tag. Set relevant attributes of the input element, for example: TYPE (e.g. button, checkbox); VALUE (its label); ONCLICK (the action to be taken when it’s clicked - event handler). 34

35 1- Unit eight : Adding GUI components to programs
Here is an example of the code for creating a form with a button. <HEAD> <TITLE>Program_8.4.1</TITLE> <SCRIPT> // JavaScript code will go in here </SCRIPT> </HEAD> <BODY> <FORM NAME = "greeting"> <INPUT TYPE = "button“ VALUE = "Press Me" ONCLICK = "window.confirm(‘You just pressed the button?')"> </FORM> Displays a dialogue box with two buttons, ‘OK’ and ‘cancel’ 35

36 1- Unit eight : Adding GUI components to programs
Adding a button and a text box… <INPUT TYPE = "button“ VALUE = "Press Me" ONCLICK = "document.greeting.response.value = 'Hello world!'"> <INPUT TYPE = "text“ NAME = "response" VALUE = ''> 36

37 1- Unit eight : Using functions as event handlers
<INPUT TYPE = "button" VALUE = "Student Details" ONCLICK = "displayDetails()"> function displayDetails() { document.details.name.value = 'Josie Bloggs'; document.details.identifier.value = 'P '; document.details.course.value = 'M150' } Invokes the function displayDetails() Name, identifier and course are the names of three text boxes The form’s name 37

38 1- Unit eight : A units conversion program
Precision of two decimal places function twoDPs(anyNumber) { return Math.round (100 * anyNumber) / 100 } function toGallons(numberOfLitres) return twoDPs(numberOfLitres * ) <INPUT TYPE = "text" NAME = "litres" VALUE = ''> <INPUT TYPE = "button" VALUE = "Convert" ONCLICK = "document.converter.gallons.value = toGallons(document.converter.litres.value)"> NAME = "gallons" Converts litres to gallons Text box to read the value in liters Converted value is displayed at a click of the button Text box to display the value in gallons 38

39 1- Unit eight : Strings A string is any sequence of letters, digits, punctuation and other special characters. JavaScript String objects provide a collection of basic methods to assist us with string processing. For example, if the variable myString currently has the value 'Hello world!' then myString.length will return the value 12 and myString.charAt(4) will return the value 'o‘. 39

40 1- Unit eight : More strings
If myString currently has the value 'Hello world!', myString.indexOf('Hell') returns 0 myString.indexOf('world') returns 6 myString.indexOf('r') returns 8 myString.indexOf('low') returns –1 40

41 1- Unit eight : Some character-processing functions
Testing a character – digit, alphabetic or alphanumeric function isNumeric(aCharacter) { return (aCharacter >= '0') && (aCharacter <= '9') } function isLowerCase(aCharacter) return (aCharacter >= 'a') && (aCharacter <= 'z') function isUpperCase(aCharacter) return (aCharacter >= 'A') && (aCharacter <= 'Z') A function to test if the character is numeric A function to test if the character is lower case A function to test if the character is upper case 41

42 1- Unit eight : Some character-processing functions
function isAlpha(aCharacter) { return (isUpperCase(aCharacter) || sLowerCase(aCharacter)) } function isAlphaNumeric(aCharacter) return (isAlpha(aCharacter) || isNumeric(aCharacter)) A function to test if the character is alphabetic A function to test if the character is alphabetic or numeric 42

43 1- Unit eight : Password checking program - rules
The rules for our password checker are as follows. The password should be between four and eight characters. The password should contain only alphanumeric characters. The password should always start with an alphabetic character. The password should always contain at least one digit. Let us take a look at a structured English algorithm required for the processing. 43

44 1- Unit eight : Password checking program - algorithm
initialise errorFound to false/prompt user to enter password and read it in. if the length is not in the range warn the user and set errorFound to true end if if not all characters are legal if the first character is not alphabetic if the password does not contain a digit if errorFound is false inform user that password is acceptable 44

45 1- Unit eight : Password checking program - code
For each of the first four tests above we will write a separate function. checkLength() - checkLegal() checkFirst() - checkHasDigit() function checkLength(aString) { return (aString.length >= 4) && (aString.length <= 8) } function checkFirst(aString) return isAlpha(aString.charAt(0)) Returns true if the string is between 4 and 8 characters Returns true if the first character is alphabetic 45

46 1- Unit eight : Password checking program - code
function checkLegal(aString) { var result; result = true; for (var position = 0; position < aString.length; position = position + 1) if (!isAlphaNumeric(aString.charAt(position))) result = false } }; return result Returns true if all characters are either alphabetic or numeric 46

47 1- Unit eight : Password checking program - code
function checkHasDigit(aString) { var result; var position; result = false; position = 1; // loop while digit not found and there are more characters to check while ((result == false) && (position < aString.length)) if (isNumeric(aString.charAt(position))) result = true } else // move to next position position = position + 1 return result Returns true if the string contains at least one digit. 47

48 1- Unit eight : Password checking program - code
function doChecks(password) { var errorFound; errorFound = false; if (!checkLength(password)) errorFound = true; window.alert('length not in range (4-8)') }; if (!checkLegal(password)) window.alert('illegal characters in password (must all be alphanumeric)') if (!checkFirst(password)) window.alert('first character must be alphabetic') if (!checkHasDigit(password)) window.alert('must contain at least one digit (but not the first character)') if (!errorFound) window.alert('password accepted') } 48

49 2- What’s next This is the last session for this semester.
Be well prepared for the midterm exam. 49

50 3- Review questions What do we call the location of an element in arrays? What is an algorithm? Write JavaScipt code for entering grades of students for M150 Section. Write code for the following two function: first (returns the first element of an array)and last (returns last element). Do we have multidimensional arrays in JavaScript? What do we call a function that does not return a value? Name some advantages of Graphical User Interface. How does the event-driven model work? What is an event handler? What is a GUI widget? What is a string?

51 4- Your questions ?


Download ppt "M150: Data, Computing and information"

Similar presentations


Ads by Google