1 / 94

M150 – Unit 7 Data, Computing and Informati

Dammam Branch. M150 – Unit 7 Data, Computing and Informati. Unit Seven: An Introduction to programming using JavaScript. What is JavaScript (JS)? A Sample Program JavaScript Variables Data types Operators Prompt box Programming for selection (the if statement)

Download Presentation

M150 – Unit 7 Data, Computing and Informati

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. Dammam Branch M150 – Unit 7Data, Computing and Informati Haifaa Elayyan

  2. Unit Seven: An Introduction to programming using JavaScript 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) 2 2

  3. Unit Seven: An Introduction to programming using JavaScript 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. 3 3

  4. Unit Seven: An Introduction to programming using JavaScript 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 4 4

  5. What is the JavaScript? • 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 5 5

  6. Section 2: Getting started 2.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> 12/1/2014 6 6

  7. 2.1 First program..count <script LANGUAGE=‘JavaScript’> tag: • Every thing between <script>and </script>is written in a scripting language. • The LANGUAGEattribute defines the scripting language, in our case ‘JavaScript’. • JavaScriptis the default language, so that if no specific language is specified, HTML will assume that the code is JavaScript. • </Script> ends the <script> tag. 12/1/2014 7 7

  8. 2.1 First program..count document.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). 12/1/2014 8 8

  9. 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: 12/1/2014 9 9

  10. 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: varmyVar; 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; 12/1/2014 10 10

  11. 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 varcarName=‘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 varcarName=“Volvo”; 12/1/2014 11 11

  12. 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. 12/1/2014 12 12

  13. 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. 12/1/2014 13 13

  14. Naming variables .. continue Example: (displaying the value of a variable) <HTML> <HEAD> <TITLE> Variables Example </TITLE> <SCRIPT LANGUAGE = "JavaScript"> varmyAge; 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? 12/1/2014 14 14

  15. Data Type • Number typesuch as 3,7,3.25,-2.27, -6 • Many programming languages treat whole numbers differently from real numbers, but JavaScript does not. • String typesuch as ‘hello’, ‘welcome’, ‘have a nice day’. Operators 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 12/1/2014 15 15

  16. Operators • Precedence of operators: • The parenthesis has the highest precedence • Multiplication and division have a higher precedence than addition and subtraction. Operators in order of decreasing precedence 12/1/2014 16 16

  17. 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= 8 And finally the value 8 is assigned to num 12/1/2014 17 17

  18. 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” 12/1/2014 18 18

  19. 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’,’’); 12/1/2014 19 19

  20. 2.5 Getting data from a user and displaying results .. continue • Example: • var name; • name = window.prompt (‘Enter your name’, ‘’); • document.write (‘Hello ‘ + name + ’!’ ); • 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. 12/1/2014 20 20

  21. 2.5 Getting data from a user and displaying results .. continue • Example: • var name; • name = window.prompt (‘Enter your name’, ‘’); • document.write (‘Hello ‘ + name + ’!’ ); • 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. 12/1/2014 21 21

  22. 2.5 Getting data from a user and displaying results .. continue • Getting 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. 12/1/2014 22 22

  23. 2.5 Getting data from a user and displaying results .. continue Getting 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 12/1/2014 23 23

  24. 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"> varfirstNumber, 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. 12/1/2014 24 24

  25. 2.5 Getting data from a user and displaying results .. continue • Getting 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. 12/1/2014 25 25

  26. Section 3: Programming for Selection: The “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. 12/1/2014 26 26

  27. 3.1 Booleans and the comparison operators 12/1/2014 27 27

  28. 3.1 Booleans and the comparison operators • Comparison operators work on any values which are ordered (strings, characters,..) Example: 12/1/2014 28 28

  29. 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) } Execute the statements before the if statement Evaluate the Boolean expression false true Execute the statement(s) in braces Ignore the statement(s) in braces Carry on with the rest of the program 12/1/2014 29 29

  30. 3.2 Simple conditional statements .. continue 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. varpassword,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') 12/1/2014 30 30

  31. 3.2 Simple conditional statements .. continue The if... elsestatement 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) } 12/1/2014 31 31

  32. 3.2 Simple conditional statements .. continue The if... elsestatement Example: Edit Activity 7.3.4 so that It prints “Your password is successfully changed” when the passwords match. varpassword,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') 12/1/2014 32 32

  33. 3.2 Simple conditional statements .. continue The if... elsestatement 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') } 12/1/2014 33 33

  34. 3.2 Simple conditional statements .. continue 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. 12/1/2014 34 34

  35. 3.2 Simple conditional statements .. continue Using comments: Example: // allocating two variables for password varpassword,repeatPassword; password = window.prompt('Please enter your password',''); repeatPassword = window.prompt('Please re-enter yourpassword',''); /* testing whether the two values match Then displaying Thank you */ if (password != repeatPassword) document.write('Your password is unchanged' + '<BR>') document.write('Thank you') 12/1/2014 35 35

  36. 3.4 An introduction to more complex conditions 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) 12/1/2014 36 36

  37. 3.4 An introduction to more complex conditions .. 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!') } } 12/1/2014 37 37

  38. 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. 38

  39. 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.

  40. 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

  41. 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)

  42. 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

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

  44. 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. 1 2 3 4 5 6 7 8 Introduction to Arrays (2) 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. 0 1 2 3 4 5 6 7 Introduction to Arrays (3) 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. 0 1 2 3 4 5 6 7 Introduction to Arrays (4) An array of houses in BoringStreet • JavaScript syntax for referring to elements in an array 5 Boring Street becomes ...... array name index number notice the square brackets BoringStreet[5]

  49. 0 1 2 3 4 5 6 7 Introduction to Arrays (5) • In JavaScript you must declare an array before you can use it e.g. notice the round brackets var BoringStreet = new Array(8); BoringStreet[5] = 'Billy Beanbag'; window.alert(BoringStreet[5]); 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

More Related