1 / 35

M150: Data, Computing and Information

M150: Data, Computing and Information. Unit Seven: An introduction to programming using JavaScript. 1- Introduction. The aims of this unit are: Writing code to read in data from a user, perform some simple processing and display the result;

Download Presentation

M150: Data, Computing and Information

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. M150: Data, Computing and Information Unit Seven: An introduction to programming using JavaScript

  2. 1- Introduction The aims of this unit are: Writing code to read in data from a user, perform some simple processing and display the result; Programming for sequence, selection and repetition in a high-level language, specifically: How to achieve selective execution of sections of program code as a result of the evaluation of some condition; How to achieve repeated execution of a section of program code, either while a particular condition is true or for a specified number of times. JavaScript is not the same as Java. Although JavaScript code looks a bit like Java, and the two languages are often used together to produce web-based applications, they are otherwise unrelated. JavaScript is case sensitive (JavaScript interpreter treats If, IF and if as being different. 2

  3. 1- Introduction Notes: Syntax : rules of the language Semantics: explain the meaning of the word in the P.L. Keywords (reserved words): words which have a special meaning in the particular programming language All the reserved words in JavaScript are lower case You must access to your computer, as it contains a large number of practical activities You should read the Block 2 Software Guide The Block 2 Software Guide tells you how to find and run the programs that we have provided, how to look at and possibly change the program source code, i.e. the set of JavaScript statements which make up the program. It also contains a summary of JavaScript syntax, which you will probably find helpful. 3

  4. 2- Getting started JavaScript, is a scripting language. This means that programs written in JavaScript cannot be run on their own, but have to be run within some application, such as a web browser. (Most high-level programming languages are not scripting languages, and do not require an additional application in which to run) JavaScript is an interpreted language. A browser such as Netscape, which has an embedded JavaScript interpreter, takes your JavaScript statements and interprets them, i.e. it translates them into machine code instructions and executes them instruction by instruction. 4

  5. 2- Getting started First program <HTML> <HEAD> <TITLE> Program_7.2.1 First Program </TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.write('Welcome to programming!') </SCRIPT> </HEAD> <BODY> </BODY> </HTML> inform the HTML system that the lines of code between them are not HTML instructions but are written in JavaScript is the instruction to display the text Welcome to programming! - document (current page) is a kind of program structure called an object. Each object is associated with particular behavior - write() is a (behaivor) method associated with the document, which enables JavaScript to add text to the page. 5

  6. 2- Getting started <SCRIPT LANGUAGE = "JavaScript"> ….. </SCRIPT> If no specific language is specified, HTML will assume that the code is JavaScript, so the first of the HTML lines above could be replaced by <SCRIPT> Notes about document.write() The ‘dot notation’ (as in document.write()) tells the document object to execute the code of its write() method The parentheses () enclose what is called 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. JavaScript will accept either single or double quotes, but in M150 we will be using single quotes 6

  7. 2- Getting started Variables A variable can be thought of as a named (or identifier) location in the computer’s memory where a value is stored. Identifier is a variable name. we don’t need to know anything about exact memory locations (JavaScript interpreter and the operating system will then identify a suitable memory location and manage it for us) The value in a variable can change (vary) as the program executes To declare a variable, use the keyword var var sum; sum = 3; document.write(sum) 3 ? Variable named sum has the value 3 Sum Sum Output 3 7

  8. 2- Getting started Notes about the previous code: Notice that sum is not enclosed in quotes, as we want to display the value of the variable called sum, not the text ‘sum’ document.write(sum) document.write(‘sum’) The semicolon can be used as a separator between instructions, so that JavaScript clearly ‘knows’ where one instruction ends and another begins. Where each instruction is on a separate line the semicolons are not mandatory, but we think they make the code clearer and will be using them throughout this block Each of the previous instructions is complete without semicolon var myVar; document.write(myVar); This is because the variable has not had any value assigned to it 3 sum undefined 8

  9. 2- Getting started Some error: document.write(hi there!) document.write(‘hi there!’) Initialization: the process of assigning an initial value to a variable Some useful data types: Number type: 3, 7, -6, 3.24 String type (Character sequences) Strings in JavaScript code must be enclosed in quotation marks to distinguish them from variables and reserved words The quotes are not actually part of the string Strings can include spaces, numbers, punctuation marks …. ‘6123’ : to indicate to JavaScript that a sequence of numbers is treat as a string Correction 9

  10. 2- Getting started Identifier must follow particular rules ( variables and methods must be valid identifiers): The first character must be one of the following an upper-or lower-case letter (that is, A...Z, a...z); an underscore character ( _ ); a dollar sign ($). Subsequent characters may be any of the above or a digit (0-9) You may not use a reserved word which is already part of JavaScript’s vocabulary. (var, while, if, for) Guidelines to make program easier to read and debug: There is no limit on the number of characters that can be used in an identifier. Avoid very short identifiers (not informative) Avoid the use of $ and _ in identifiers. Choose meaningful names Start your identifiers with lower-case letters 10

  11. 2- Getting started Assignment operator( = ) Any value on the right of the = symbol, is assigned to the variable named on the left When assigning a value to a variable, the name of the variable must be on the left-hand side of the = symbol, and the value on the right. The right side can be explicit value, an expression that will evaluate to a value, or other variable name var myVar, yourVar; myVar = 6; yourVar = myVar + 3; myVar = yourVar; 3 = myVar;  error statement If a new value is assigned to the variable, then this value overwrites the previous value, which is lost 11

  12. 2- Getting started Operators on numbers (binary operators): Addition + Subtraction – Multiplication * Division / Precedence rules: The order in which they are applied in an expression containing more than one operator Parentheses: evaluate the expression (s) in parentheses first, and where there is more than one set, the expression in the innermost pair will be evaluated first. Multiplication and division Addition and subtraction. 12

  13. 2- Getting started (2 * (3 + (6 / (1 + 2)) - 1)) (2 * (3 + (6 / (1 + 2)) - 1)) (2 * (3 + (6 / 3) - 1)) (2 * (3 + 2 - 1)) (2 * (5 - 1)) (2 * 4) 8 A binary operator on strings The symbol + is also used as a string operator: in this context + is the operator for concatenation (appending the second string to the first). For example: 'Hello' + 'there' will give 'Hellothere' 13

  14. 2- Getting started Getting data from a user and displaying results: var name; name =window.prompt('Enter your name',''); document.write('Hello ' + name + '!'); document.write('<BR>' + 'Have a good day') Output Hello Ali!Have a good day Ali instructs JavaScript to display a prompt dialogue box with some specified text. This box lets you enter a value, which is then assigned to the variable 14

  15. 2- Getting started Notes: window refers to the browser’s window in which document (the current page) is displayed. The method prompt() is associated with window object, which cause the prompt dialogue box to appear on top of the window prompt() can be used with two arguments, separated by a comma. The first argument specifies the string that the programmer wants to appear in the box; the second specifies a default response string, which appears in the text entry box before the user has entered any value In the previous example, the default string is the empty string ''. It is not the same as ' ', which is two single quotes with a space JavaScript treats all input and output in prompt box as strings, so does not need the quotes to distinguish them <BR> at line 4 (HTML tag ), creates a line break (causes the text which comes after it to be displayed on a new line) 15

  16. 2- Getting started Example: var name; var day; name = window.prompt('Enter your name','Type your name here'); day = window.prompt('Enter the day',''); document.write('Hello ' + name + '!'); document.write('<BR>' + 'Have a nice ' + day) Output if the inputs are Ali , Sunday Hello Ali! Have a nice Sunday Type your name here 16

  17. 2- Getting started If you enter the two numbers 32 and 45, the output will be: The sum of 32 and 45 is 3245 • Example: var numberOne; var numberTwo; var sum; numberOne = window.prompt('Enter your first number',''); numberTwo = window.prompt('Enter your second number',''); sum = numberOne + numberTwo; document.write('The sum of '+ numberOne + ' and ' + numberTwo + ' is ' + sum) JavaScript have understood + to be concatenation operator 17

  18. 2- Getting started Function parseFloat(): Takes a string as an argument and provides as a result (return value) the number corresponding to the numeric part of the string – converting a suitable string into a number. parseFloat('3') returns 3 parseFloat('10.25') returns 10.25 parseFloat(‘04') returns 4  leading zero will be lost myVar = window.prompt('Enter a number',''); myVar = parseFloat(myVar) parseFloat() will not be able to convert characters into numbers. It will return NaN ‘Not a Number ‘ parseFloat(‘three') returns NaN Outputting numbers: The argument of the document.write() must be a string. If the argument is number; the method write() takes a number, say 183, and automatically converts it to the string '183' 18

  19. 2- Getting started • Example: var firstNumber; var secondNumber; var 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) • If you enter 32 and 45, the output will be: The sum of 32 and 45 is 77 • If you enter thirty-two and forty-five, the output will be: The sum of NaN and NaN is NaN 19

  20. 3- Programming for selection: the if statement Boolean data type: consists of just two values, true and false Boolean expression: is the condition which returns a Boolean value Comparison operators: act on compare two values of the same type, such as two number or two string and return a Boolean value 20

  21. 3- Programming for selection: the if statement Example: var firstValue, secondValue; var firstBool, secondBool; firstValue = window.prompt('Please enter your first value',''); firstValue = parseFloat(firstValue); secondValue = window.prompt('Please enter your second value',''); secondValue = parseFloat(secondValue); firstBool = (firstValue < secondValue); secondBool = (firstValue <= secondValue); document.write('It is ' + firstBool + ' that '+ firstValue + ' < '+ secondValue); document.write('<BR>' + 'It is ' + secondBool + ' that '+ firstValue + ' <= ' + secondValue) If you enter 3 then 5, the output will be: Several variables can be declared on the same line consisting of the reserved word var followed by the names of each of the variables, separated by commas. We recommend that you put variables of different kinds on different lines It is true that 3 < 5 It is true that 3 <= 5 21

  22. 3- Programming for selection: the if statement Notes: Leaving a space between operator(<=, !=, … ) will cause a syntax error. Use of a ‘double equals’ (==) symbol for the equality operator. This distinguishes it from the assignment operator =. All operators are binary operator. We can use the comparison operators on any values which are ordered (letters, numbers) Comparisons on strings work by comparing the first letter in each string, then, if they are the same, the second letter in each string, and so on. (‘a’ < ‘c’)  true ('cat' < 'cave')  true ('cat' < 'camel')  false (‘117’ < ‘32’)  true but (117 < 32) false 22

  23. 3- Programming for selection: the if statement Conditional statements: The if statement If (Boolean expression) { Statement (s) }; Carried out only when a certain condition is true 23

  24. 3- Programming for selection: the if statement Example: (1) var bankBalance, withdrawalAmount; (2) bankBalance = 100; (3) withdrawalAmount = window.prompt('How much do you want to withdraw?',''); (4) withdrawalAmount = parseFloat(withdrawalAmount); (5) if (withdrawalAmount > bankBalance) (6) { (7) document.write('You cannot do that!' + '<BR>') (8) }; (9) document.write('Goodbye') If the input is 100: Goodbye If the input is 50: If the input is 150: Goodbye You cannot do that Goodbye 24

  25. 3- Programming for selection: the if statement Notes: The Boolean expression which follows the reserved word if must be within parentheses. The spacing and indentation are purely to aid readability Where there is a statement following the if statement, a semicolon is needed after the closing brace (curly bracket) in order to separate the if statement from the next statement . Testing programs: it’s important to choose a set of test inputs that are likely to find any errors. For if statements, you should test with at least two values, one which makes the condition true (the route by which the statement (s) within the braces are executed), and one which makes it false (the route by which they are ignored). It is better to choose a boundary values (values at and around) 25

  26. 3- Programming for selection: the if statement Example: The program prompts you to enter a password, and then prompts you to re-enter the password. It then checks whether the two entries 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>') }; document.write('Thank you') If inputs are: abc, abc If inputs are: ab, abc Thank you Your password is unchanged Thank you 26

  27. 3- Programming for selection: the if statement The if … else statement Do one thing if a condition is true and something else if the condition is false if (Boolean expression) { statement(s) } else { different statement(s) } ; there is no semicolon before the else. 27

  28. 3- Programming for selection: the if statement Example: var password, repeatPassword; password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter your password',''); if (password != repeatPassword) { document.write('Your password is unchanged' + '<BR>') } else { document.write ('Password successfully changed' + '<BR>') }; document.write('Thank you') If inputs are: abc, abc Password successfully changed Thank you 28

  29. 3- Programming for selection: the if statement Example: var response; response = window.prompt('Are you having a good day today?', ''); if (response == 'Yes') { document.write('Glad to hear it') } else { document.write('Maybe tomorrow will be better') }; document.write('<BR>' + 'Thank you for replying') Don’t use = instead of == If the input is: yes If the input is: Yes Maybe tomorrow will be better Thank you for replying Glad to hear it Thank you for replying 29

  30. 3- Programming for selection: the if statement Conditionals and compound statements Compound statements: several statements (separated by semicolons or new line characters) enclosed in braces { } – treats as a single statements. The use of braces where only a single statement appears in an if or an else clause is not strictly necessary, but we recommend that you use them as it makes the code more readable Improving readability by using comments Readability can be improved by the use of meaningful variable names and by using indentation and spacing to show the structure of your code. Code can be clearer if it include comment JavaScript provides two ways of comments: The symbol // (two forward slashes) tells JavaScript to ignore anything on the remainder of that line The pair of symbols /* and */ tells JavaScript to ignore anything between them 30

  31. 3- Programming for selection: the if statement Example var yearOfBirth, thisYear; yearOfBirth =window.prompt('Please enter your year of birth',''); yearOfBirth = parseFloat(yearOfBirth); thisYear = window.prompt('Please enter the current year', '2004'); thisYear = parseFloat(thisYear); if (yearOfBirth > thisYear) { document.write('You have made a mistake somewhere'); yearOfBirth = window.prompt('Please re-enter your year of birth',''); yearOfBirth = parseFloat(yearOfBirth); thisYear = window.prompt('Please re-enter the current year', '2004'); thisYear = parseFloat(thisYear) }; document.write('<BR>' + 'On your birthday this year, you will be' + (thisYear -yearOfBirth)) 31

  32. 3- Programming for selection: the if statement An introduction to more complex conditionals Compound Boolean expression NOT is a unary Boolean operator ( ! ) - if a is true, !(a) is false; if a is false, !(a) is true. OR is a binary Boolean operator ( || ) - if either a or b is true, or both are true, (a || b) is true; otherwise (a || b) is false. AND is a binary Boolean operator ( && ) - if both a and b are true, (a && b) is true; otherwise (a && b) is false. Evaluate the following expression If x is 21? (a) ((x == 21) && (x > 22))  false (b) !(x >= 21)  false (c) ((x > 15) || (x < 12))  true 32

  33. 3- Programming for selection: the if statement Nested conditionals if (condition_1) { statement(s)_1 } else { if (condition_2) { statement(s)_2 } else { if (condition_3) { statement(s)_3 } else { statements } } } 33

  34. 3- Programming for selection: the if statement Example: 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!') } } } The symbol \ in today\'s tells JavaScript that the quote is part of the string, not the string terminator. The \ is referred to as an escape character It is hot ! If the input is 25 It is cold If the input is 11 It is freezing If the input is -2 It is a nice day If the input is 24 34

  35. 3- Programming for selection: the if statement Example var mark; mark = window.prompt('Please enter your mark',''); mark = parseFloat(mark); if (mark < 40) { document.write('Sorry, you\'ve failed') } else if (mark < 60) { document.write('Congratulations, you\'ve passed') } else { document.write('Many congratulations, you have honours') } You should run the program to test three possible routes, one when the input is less than 40, one when it is 40 or over but less than 60 and one when it is greater than or equal 60 We have not included braces round the else clause that goes with the first if, because the else clause is a single statement 35

More Related