M150 – Unit 7 Data, Computing and Informati
-
Upload
charity-hebert -
Category
Documents
-
view
33 -
download
0
description
Transcript of M150 – Unit 7 Data, Computing and Informati
M150 – UNIT 7DATA, COMPUTING AND
INFORMATI1
Haifa
a E
layyan
UNIT SEVEN: AN INTRODUCTION TO UNIT SEVEN: AN INTRODUCTION TO PROGRAMMING USING JAVASCRIPTPROGRAMMING USING JAVASCRIPT
22
What is JavaScript (JS)? A Sample Program JavaScript Variables Data types Operators Prompt box Programming for selection (the if statement) Programming for repetition (the while statement) Programming for repetition (the for statement)
UNIT SEVEN: AN INTRODUCTION TO UNIT SEVEN: AN INTRODUCTION TO PROGRAMMING USING JAVASCRIPTPROGRAMMING USING JAVASCRIPT
33
What is a scripting language ?
A scripting language, script language or extension language, is a programming language that allows some control of a single or many software application(s). "Scripts" are often treated as distinct from "programs", which execute independently from any other application. At the same time they are distinct from the core code of the application, which is usually written in a different language, and by being accessible to the end user they enable the behavior of the application to be adapted to the user's needs. Scripts are often, but not always, interpreted from the source code or "semi-compiled" to bytecode which is interpreted, unlike the applications they are associated with, which are traditionally compiled to native machine code for the system on which they run. Scripting languages are nearly always embedded in the application with which they are associated.The name "script" is derived from the written script of the performing arts, in which dialogue is set down to be spoken by human actors. Early script languages were often called batch languages or job control languages. Such early scripting languages were created to shorten the traditional edit-compile-link-run process.
UNIT SEVEN: AN INTRODUCTION TO UNIT SEVEN: AN INTRODUCTION TO PROGRAMMING USING JAVASCRIPTPROGRAMMING USING JAVASCRIPT
44
What is JAVASCRIPT language ?
JavaScript is a scripting language widely used for client-side web development. It was the originating dialect of the ECMAScript standard. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languages and was designed to look like Java, but be easier for non-programmers to work with
What is the JavaScript?
55
JavaScript was designed to add interactivity to HTML pages.
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
Everyone can use JavaScript without purchasing a license
JavaScript is used to improve the design, validate forms, detect browsers, create cookies, and much more.
JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, and Opera
6604/19/2304/19/23
Section 2: Getting startedSection 2: Getting started2.1 First program
<HTML><HEAD>
<TITLE> Activity_7.2.2 First Program</TITLE>
<SCRIPT LANGUAGE = "JavaScript"> document.write('Welcome to programming!')</SCRIPT>
</HEAD>
<BODY></BODY>
</HTML>
7704/19/2304/19/23
2.1 First program..count
<script LANGUAGE=‘JavaScript’> tag: Every thing between <script> and </script> is written in a scripting language.
The LANGUAGE attribute defines the scripting language, in our case ‘JavaScript’.
JavaScript is the default language, so that if no specific language is specified, HTML will assume that the code is JavaScript.
</Script> ends the <script> tag.
8804/19/2304/19/23
2.1 First program..countdocument.write(‘Welcome to programming!’) : The word document.write is a standard JavaScript command for writing output to a page.
document is an object consisting of the contents of the current page that will be displayed in a window opened by the browser.
write() is a method associated with the document object, which enables JavaScript to add text to the page.
The ‘dot notation’ (in document.write()) tells the document to execute the code of its write() method.
The parenthesis () enclose the argument of the method. It provides information that the method needs to do its job, which, in this case, is the text to be displayed.
The text in the program statement must be enclosed in quotation marks (either double or single quotes).
9904/19/2304/19/23
2.1 First program..count
Save the program as sample.html and double click on it. The following line will appear on the screen as follows:
101004/19/2304/19/23
2.2 Variables and sequential execution A variable is a named location in the computer’s memory where a value is stored.
The value of a variable can change as the program executes.
Declaring variables:
var myVar;
The keyword var is used to declare a variable named myVar. myVar doesn’t yet have a value.
A group of variables can be declared in one statement
var var1, var2, var3;
111104/19/2304/19/23
2.2 Variables and sequential execution .. continue
Assigning values to variables:
myVar = 5;
The assignment operator = is used to assign the value on its right (5) to the variable on its left (myVar).
5=myVar is invalid
You can assign values to the variables when you declare them
var carName=‘Volvo’;
If you assign values to variables that have not yet been declared, the variables will automatically be declared.
ex: carName="Volvo"; has the same effect as var carName=“Volvo”;
121204/19/2304/19/23
Naming variables
Naming Variables: Names for variables are sometimes refer to as identifiers.
An Identifier is a name that must follow particular rules.
Because JavaScript is case-sensitive, variable names are case-sensitive. ex: total and Total are two different variables.
Variable names must begin with a letter, the underscore _ character or the $ character.
Don’t use a reserved word which is already a part of JavaScript’s vocabulary (such as var, if, for, while..) while naming variables.
131304/19/2304/19/23
Naming variables .. continue
Naming Variables: When choosing identifiers for your variables:
Avoid very short identifiers such as a, b, x, ch.., because they are not very informative.
Avoid the use of $ and _ in identifiers.
Choose meaningful names that give some indication of the role played by the variable.
ex: var price for the price of an item.
Start your identifiers with lower-case letters. When an identifier is composed of more than one word, use single upper-case letter to mark the start of each word.
ex: myFamilyName, netWeight.
141404/19/2304/19/23
Naming variables .. continueExample: (displaying the value of a variable)<HTML><HEAD><TITLE> Variables Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
var myAge;myAge=23;document.write(myAge);
</SCRIPT></HEAD><BODY></BODY></HTML>
this program will print 23 on the screen.Q: what will happen if we write document.write(‘myAge’) instead?
151504/19/2304/19/23
Data Type Number type such as 3,7,3.25,-2.27, -6
Many programming languages treat whole numbers differently from real numbers, but JavaScript does not.
String type such as ‘hello’, ‘welcome’, ‘have a nice day’.
Operators on numbers:Assignment operator = ; Addition operator + ;
Subtraction operator –
Multiplication operator * ; Division operator /
Ex: myVar=yourVar + 3
sum=9 + 7 / 2
Average=22 – 6 * 3
Operators
161604/19/2304/19/23
OperatorsPrecedence of operators: The parenthesis has the highest precedence Multiplication and division have a higher
precedence than addition and subtraction.
Operators Associativity
() Left to right
* / Left to right
+ - Left to right
= Right to left
Operators in order of decreasing precedence
171704/19/2304/19/23
Operators
Example:num = (2 * (3 + (6 / (1 + 2)) –1))num= (2 * (3 + (6 / 3) –1))num= (2 * (3 + 2 – 1))num= (2 * (5-1) )num= (2 * 4)num= 8And finally the value 8 is assigned to num
181804/19/2304/19/23
Operators
Operators on strings: The symbol + is also used as a string operator to append the second string to the first string. Here + is called a concatenation operator.
Ex: ‘Hello’ + ‘World’ will give ‘HelloWorld’ ‘Hello ‘ + ‘World’ will give ‘Hello World’
If you add a number and a string the result will be string Ex: 5 + 5 =10
“5”+ 5 =“55”“5”+”5”=“55”
191904/19/2304/19/23
2.5 Getting data from a user and displaying results A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax: window.prompt ("sometext","defaultvalue"); example: name = window.prompt(‘Enter your name’,’’);
202004/19/2304/19/23
2.5 Getting data from a user and displaying results .. continueExample:1) var name;2) name = window.prompt (‘Enter your name’, ‘’);3) document.write (‘Hello ‘ + name + ’!’ );4) document.write (‘<BR>’ + ‘Have a good day’)
Example explanation:
The first line (1) just declares a variable called name.The second line (2) instructs JavaScript to display a prompt dialogue box that lets you enter your name which is then assigned to
the variable name.“window” refers to the browser’s window in which document is
displayed.The method prompt() is associated with the window object, this will
cause the prompt box to appear on the top of the window.
212104/19/2304/19/23
2.5 Getting data from a user and displaying results .. continueExample:1) var name;2) name = window.prompt (‘Enter your name’, ‘’);3) document.write (‘Hello ‘ + name + ’!’ );4) document.write (‘<BR>’ + ‘Have a good day’)
Example explanation:
The method prompt() can be used with two arguments: window.prompt ("sometext","defaultvalue");The first one to display some text and the second one specifies the
default response string which appears in the entry box before the user has entered any value.
In line (3) we use the string concatenation to make the three strings into a single string.
In line (4), we use the HTML tag <BR>, which creates a line break, and concatenate it with the string ‘Have a good day’ to form a single string.
222204/19/2304/19/23
2.5 Getting data from a user and displaying results .. continueGetting numbers as input:
All inputs from keyboard are assumed to be strings.
Example:num1 = window.prompt('Enter your first number','');num2 = window.prompt('Enter your second number','');sum = num1 + num2;document.write('The sum of' + num1 + ' and ' + num2 + ' is '
+ sum)If the user entered the two numbers 32 and 45, the expected
output will be as follows:
The sum of 32 and 45 is 77
But, in fact, the output is:
The sum of 32 and 45 is 3245
this means that + operator works as concatenation not addition.
232304/19/2304/19/23
2.5 Getting data from a user and displaying results .. continueGetting numbers as input:
What should we do to read two numbers and add them?Use parseFloat() function.
parseFloat() function takes a string and returns the number
corresponding to its numeric part.
Ex: parseFloat(‘3’) returns 3 parseFloat(’10.25’) returns 10.25
242404/19/2304/19/23
2.5 Getting data from a user and displaying results .. continue
Getting numbers as input:<HTML><HEAD><TITLE> Program_7.2.9 </TITLE><SCRIPT LANGUAGE = "JavaScript">
var firstNumber, secondNumber, total;
firstNumber = window.prompt('Enter your first number','');
firstNumber = parseFloat(firstNumber);
secondNumber = window.prompt('Enter your second number','');
secondNumber = parseFloat(secondNumber);
total = firstNumber + secondNumber;
document.write(' The sum of '+ firstNumber + ' and '+ secondNumber+ ' is ' +
total)</SCRIPT></HEAD><BODY></BODY></HTML>Try this (tutor) and see the output.
252504/19/2304/19/23
2.5 Getting data from a user and displaying results .. continueGetting numbers as input:
Not all the numbers entered by the prompt box should be converted into float. You have to know where to use parseFloat().
If we have to do some calculations to numbers, we use parseFloat(), otherwise not.
ex: telephone = window.prompt(“Enter your telephone number”,’’)
If the user entered the value: “03679858”, after parseFloat() the value of telephone will be: 3679858 which is incorrect.
262604/19/2304/19/23
Section 3: Programming for Selection:Section 3: Programming for Selection:The “if” statmentThe “if” statment
3.1 Booleans and the comparison operators
We need to add some conditions to our program
To write conditions in JavaScript, you should use comparison operators.
Comparison operators are used to decide whether a condition is true or false.
Comparison operators act on two values of same type and return a Boolean value.
272704/19/2304/19/23
3.1 Booleans and the comparison operatorsOperator symbol Informal
description Discussion Examples
< less than (a<b) is true if the value of a is less than the value of b, otherwise it is false
(3 < 5) true
(7 < 2) true
(3 < 3) false
<= less than or equal to (a <= b) is true if the value of a is less than the value of b, or is equal to the value of b, otherwise it is false
(2 <= 5) true
(2 <= 1) false
(2 <= 2) true
> greater than (a > b) is true if the value of a is greater than the value of b, otherwise it is false
(2 > 3) false
(2 > 1) true
(2 > 2) false
>= greater than or equal to (a >= b) is true if the value of a is greater than the value of b, or is equal to the value of b, otherwise it is false
(3 >= 2) true
(3 >= 5) false
(3 >= 3) true
== equal to (a==b) is true if the value of a is equal to the value of b, otherwise it is false
(2 == 3) false
(2 == 2) true
!= not equal to (a!=b) is true if the value of a is not equal to the value of b, otherwise it is false
(3 != 2) true
(2 != 3) true
(2 != 2) false
282804/19/2304/19/23
3.1 Booleans and the comparison operators Comparison operators work on any values which are ordered (strings, characters,..)
Example:
(‘a’<‘c’) True
(‘cat’<‘cave’) True
(‘177’<‘45’) True
(‘cat’<‘camel’) False
292904/19/2304/19/23
3.2 Simple conditional statements The if statement asks the computer to do something when a condition is true. The general form of the if statement is:
if (Boolean Expression){ statement(s)}
Carry on with the rest of the program
Execute the statement(s) in braces
Execute the statements before the if statement
Evaluate the Boolean
expression
true false
Ignore the statement(s) in braces
Example: (Activity 7.3.4)
The following program prompts the user to enter a password, and then prompts him to re-enter the password.
It then checks whether the two entries match. If they don’t, the program displays “Your password is unchanged”.
Whether or not they match, it displays “Thank you” on a new line on the screen.
var password,repeatPassword;
password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter yourpassword','');
if (password != repeatPassword){
document.write('Your password is unchanged' + '<BR>')};
document.write('Thank you')
3.2 Simple conditional statements .. continue
303004/19/2304/19/23
The if... else statement
The if..else statement asks the computer to do one thing if a condition is true and something else if the condition is false.
Syntax of if..else statement:
if ( Boolean Expression) { statement(s) }else { statement(s) }
3.2 Simple conditional statements .. continue
313104/19/2304/19/23
The if... else statement
Example:
Edit Activity 7.3.4 so that It prints “Your password is successfully changed” when the passwords match.
var password,repeatPassword; password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter yourpassword','');if (password != repeatPassword) document.write('Your password is unchanged' + '<BR>');else document.write('Your password is successfully changed' + '<BR>');
document.write('Thank you')
3.2 Simple conditional statements .. continue
323204/19/2304/19/23
The if... else statement
The statements in both the if clause and else clause could be either simple or compound statement.
Compound statement is a set of statements wrapped together in parenthesis { } and separated by semicolons or new line characters.
if (password != repeatPassword) document.write('Your password is unchanged' + '<BR>');else { document.write('Your password is successfully changed' + '<BR>'); document.write('Thank you')}
3.2 Simple conditional statements .. continue
333304/19/2304/19/23
Using comments:
Adding comments to the program (especially complex programs) increase the readability of it.
A comment explains what a certain statement do.
There are two symbols for comments
The short symbol // tells the JS to ignore anything on the remainder of that line.
The pair of symbols /* and */ tells JS to ignore anything between them.
3.2 Simple conditional statements .. continue
343404/19/2304/19/23
Using comments:
Example:
// allocating two variables for passwordvar password,repeatPassword; password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter yourpassword','');
/* testing whether the two values matchThen displaying Thank you */
if (password != repeatPassword) document.write('Your password is unchanged' + '<BR>')document.write('Thank you')
3.2 Simple conditional statements .. continue
353504/19/2304/19/23
More Complex Conditionals:
NOT, OR & AND can also be used in JavaScript inside if statement
! means NOT
|| means OR
&& means AND
Ex:
Either ( x > 3) or (x <= 1) ((x > 3) || (x <= 1))
Both (x > 3) and (x <= 5) ((x > 3 ) && (x <= 5))
It is not true that (x > 10) ! (x > 10)
3.4 An introduction to more complex conditions
363604/19/2304/19/23
Nested Conditionals:
Program_7.3.9
/* Program to provide descriptive information about the temperature, given its value */
var temperature;
temperature = window.prompt('Please enter today\'s current temperature in degrees Celsius', '');temperature = parseFloat(temperature);if (temperature <= 0) document.write('It is freezing')else { if (temperature < 15) document.write('It is cold') else { if (temperature < 25) document.write('It is a nice day') else document.write('It is hot!') }}
373704/19/2304/19/23
3.4 An introduction to more complex conditions ..
1- UNIT EIGHT: STRUCTURED DATA - ARRAYThere 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.
38
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.
39
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
40
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)
41
1- UNIT EIGHT: ARRAY STRUCTURE
42
111
115
200
95
23
59
68
33
39
144
66
37
rainArrayrainArray[ 0 ]
Position number (index or subscript) of the element within rainArray
rainArray[ 1 ]
rainArray[ 2 ]
rainArray[ 3 ]
rainArray[ 4 ]
rainArray[ 5 ]
rainArray[ 11 ]
rainArray[ 10 ]
rainArray[ 9 ]
rainArray[ 8 ]
rainArray[ 7 ]
rainArray[ 6 ]
1- UNIT EIGHT: ACCESSING ARRAY ELEMENTS Accessing individual elements of an array
myM150MarkArray[1] = 95
document.write(‘My Mark for TMA02 was ‘ + myM150MarkArray[1] );
43
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.
44
45
INTRODUCTION TO ARRAYS (1)
In real life we're used to the idea of referring to things by numbers e.g. houses in a street, seats in a row at the theatre
This is the idea behind arrays
46
INTRODUCTION TO ARRAYS (2)
1 2 43 5 6 7 8
A row of houses in Boring Street
Billy Beanbag lives at 5 Boring Street Deliver this to 7 Boring Street Who lives at 2 Boring Street? What is the house number of the 3rd house in Boring
Street? How many houses in Boring Street? What is the highest house number in Boring Street? Delivery one of these to all the houses in Boring Street
47
INTRODUCTION TO ARRAYS (3)
0 1 32 4 5 6 7
In JavaScript items in an array are numbered from 0
How many houses in Boring Street? What is the highest house number in Boring Street? What is the house number of the 3rd house in Boring
Street?
48
INTRODUCTION TO ARRAYS (4)An array of houses in BoringStreet
0 1 32 4 5 6 7
• JavaScript syntax for referring to elements in an array
5 Boring Street becomes ......
BoringStreet[5]
array name index number
notice the square brackets
49
INTRODUCTION TO ARRAYS (5)
0 1 32 4 5 6 7
• In JavaScript you must declare an array before you can use it e.g.
BoringStreet[5] = 'Billy Beanbag';
window.alert(BoringStreet[5]);
var BoringStreet = new Array(8);
notice the round brackets
BoringStreet_1.html
50
ARRAY EXERCISE 1 Declare an array called months that can hold
12 elements Write a JavaScript statement to make the last
element in the array hold the string "December"
Write a JavaScript statement to make the first element in the array hold the string "January"
Write a JavaScript statement to display the contents of the last element of the array
Write a JavaScript statement to display the contents of the first element of the array
51
INTRODUCTION TO ARRAYS (6)
0 1 32 4 5 6 7
• A shorthand way of declaring an array and giving it values all in one go:
var BoringStreet = ['Joe Cole', 'Frank Lampard', 'Petr Cech', 'John Terry', ' Didier Drogba', 'Billy Beanbag', 'Michael Ballack', 'Arjen Robben'];
BoringStreet_2.html
52
ARRAYS EXERCISE 2
Use the syntax given on the previous slide to declare an array called colours and assign it the values "red", "green", "blue".
53
FINDING THE NUMBER OF ELEMENTS IN AN ARRAY
window.alert(BoringStreet.length);
From the earlier slide who lives at:
BoringStreet[BoringStreet.length - 1]
0 1 32 4 5 6 7
BoringStreet_3.html
54
DISPLAYING ALL ELEMENTS IN AN ARRAY The long-winded way
document.write(BoringStreet[0]);document.write(BoringStreet[1]);document.write(BoringStreet[2]);document.write(BoringStreet[3]);document.write(BoringStreet[4]);document.write(BoringStreet[5]);document.write(BoringStreet[6]);document.write(BoringStreet[7]);
BoringStreet_4.html
55
DISPLAYING ALL ELEMENTS IN AN ARRAY
The clever way
for (var num = 0; num < BoringStreet.length; num = num + 1)
{
document.write(BoringStreet[num]);
}
0 1 32 4 5 6 7
BoringStreet_5.html
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
56
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>’)
}
57
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’,’’)
}
58
1- UNIT EIGHT : MAX VALUE OF AN ARRAY
Algorithm:Initialize maximum monthly rainfall to
rainfall in first month of the yearFor each month of the year (except the first)
Compare the month’s rainfall with the current maximumIf it is bigger replace the current maximum with this month’s value
End for
Write out the final maximum value
59
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);
60
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 2.6 - 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.
61
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.
62
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().
63
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>’)
64
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.
65
1- UNIT EIGHT: FUNCTIONS
General form of a function:
66
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;}
1- UNIT EIGHT: FUNCTIONS EXAMPLE
Function doThis(){
document.write(‘do this’ + ‘<BR>’)}
function call: doThis();
67
1- UNIT EIGHT: FUNCTIONS
Functions with ArgumentsFunction doThis(aTime){
document.write(‘do this ‘ + aTime + ‘<BR>’)
}Function call:
doThis(‘now’)
68
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 * 0.03937}
69
1- UNIT EIGHT: FUNCTIONSFunctions 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)
70
1- UNIT EIGHT: FUNCTION CALLING ANOTHER FUNCTION
71
1- UNIT EIGHT: FUNCTIONS WITH MORE THAN ONE ARGUMENT
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 characterswrite the given character
end formove to a new line
End for
72
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)}
}
73
1- UNIT EIGHT: FUNCTIONS WITH MORE THAN ONE ARGUMENT
Output:
74
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?
75
1- UNIT EIGHT : GRAPHICAL USER INTERFACEThe 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.
76
1- UNIT EIGHT : EVENTSAn 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.
77
1- UNIT EIGHT : EVENTSThese 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.
78
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. 79
1- Unit eight : Adding GUI components to programs
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). 80
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>
81
Displays a dialogue box with two buttons, ‘OK’ and ‘cancel’
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 = ''>
82
1- Unit eight : Adding GUI components to programs
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 = 'P1234567'; document.details.course.value = 'M150' }
83
The form’s name
Name, identifier and course are the names of three text boxes
Invokes the function displayDetails()
1- UNIT EIGHT : A UNITS CONVERSION PROGRAMfunction twoDPs(anyNumber) { return Math.round (100 * anyNumber) / 100 }
function toGallons(numberOfLitres) { return twoDPs(numberOfLitres * 0.21998) }
<INPUT TYPE = "text" NAME = "litres" VALUE = ''>
<INPUT TYPE = "button" VALUE = "Convert" ONCLICK = "document.converter.gallons.value = toGallons(document.converter.litres.value)">
<INPUT TYPE = "text" NAME = "gallons" VALUE = ''>
84
Precision of two decimal places
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
1- UNIT EIGHT : STRINGSA 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 andmyString.charAt(4) will return the value 'o‘.
85
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
86
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') }
87
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
function isAlpha(aCharacter) { return (isUpperCase(aCharacter) || sLowerCase(aCharacter)) }
function isAlphaNumeric(aCharacter) { return (isAlpha(aCharacter) || isNumeric(aCharacter)) }
88
A function to test if the character is alphabetic
A function to test if the character is alphabetic or numeric
1- Unit eight : Some character-processing functions
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.
89
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 trueend if
if not all characters are legal warn the user and set errorFound to trueend if
if the first character is not alphabetic warn the user and set errorFound to trueend if
if the password does not contain a digit warn the user and set errorFound to true end if
if errorFound is false inform user that password is acceptable end if
90
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))}
91
Returns true if the string is between 4 and 8 characters
Returns true if the first character is alphabetic
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 }
92
Returns true if all characters are either alphabetic or numeric
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}
93
Returns true if the string contains at least one digit.
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))
{
errorFound = true;
window.alert('illegal characters in password (must all be alphanumeric)')
};
if (!checkFirst(password))
{
errorFound = true;
window.alert('first character must be alphabetic')
};
if (!checkHasDigit(password))
{
errorFound = true;
window.alert('must contain at least one digit (but not the first character)')
};
if (!errorFound)
{
window.alert('password accepted')
}
}
94
1- Unit eight : Password checking program - code