Chapter 18 Programming Basics When it comes to being precise about an algorithm, a programming language is better than English 1 5 Cool Things… 1. 2. 3. 4. 5. Variables and Arithmetic (Today) Branches for variety (Today) Using Functions (Next week) Building your own Functions (2 weeks) Loops to repeat (3 weeks) 2 Begin with HTML HTML is static … the contents of the file are displayed as given <html><head><title>My Test Page</title></head> <body> What is 2.0 + 2.0? </body> </html> 3 JavaScript Needs HTML JavaScript must be surrounded by <script> tags in a Web page ... <html><head><title>My Test Page</title></head> <body> What is 2.0 + 2.0? <script language=“JavaScript”> Put your JavaScript code here </script> </body> </html> Script tags can be used anywhere in file 4 Browsers Process JS When the browser comes to JavaScript, it processes it immediately <html><head><title>My Test Page</title></head> <body> What is 2.0 + 2.0? <script language="JavaScript"> alert(2.0 + 2.0); </script> </body> </html> Page not fully loaded 5 JS Can Build Pages JavaScript can add to a page using the document.write command ... <html><head><title>My Test Page</title></head> <body> The sum 2.0 + 2.0 equals <script language="JavaScript"> document.write(2.0 + 2.0); </script> </body> </html> 6 JavaScript is Cool JavaScript has many slick applications We move on now to the basics, but first ... This is what is possible (UW JS project) 7 Names In Programming In normal language, names, and the things they name -- their values -- usually cannot be separated • In programming most names change values … a consequence of finite specification • Titles (US_Open_Champ), Offices (Mayor), Roles (Juliet), etc. are familiar examples of names that change values • Rules, Processes and Directions exploit the variable value: “Juliet moves to the window” 8 Some Variables and their Values Name (Identifier) Current Value Previous Values US President George Bush Bill Clinton, Abe Lincoln Chief Justice John Roberts William Renquist Warren Burger James Bond Pierce Brosnan Roger Moore, Sean Connery 9 Variables Names in programming are identifiers The things they name are their values The package -- identifier & value -- is a variable, implying a possible change • Identifiers have a specific structure in every programming language • JS: letters, digits, _ start with letter, case sen. X x textOut MI5 long_variables_are_OK rate hypens-not-OK 007 no spaces end 10 Declarations To declare variables is to state what variables will be used • Required … put declarations first in program • Use the word: var • Follow with a list of variables separated by , • Terminate all statements with a semicolon ; var x, input1, input2, rate; • Give variables an initial value with = var interestRate = 4, pi = 3.14159; 11 Quiz (answers at end of slides) Question 1: declare two variables in JavaScript to hold a person's weight and height. Question 2: declare a variable to hold a person's age and initialize it to 24. 12 Values Programming languages allow several types of values: numeric, strings of letters, Boolean • numbers: 1 • • • • • 0 -433 6.022e+23 .01 not numbers: 1,000 106 5% 7±2 strings: "abc" 'efg' " " "B&B's" "" not strings: ' '<tab>' "a ' "\" Boolean: true false not Boolean: T F yes no 13 More Quiz Question 3: Which declarations are expressed incorrectly or with illegal values var Pres=“Bush”; var city=“Rome’; var money=$1.50; var age=42,000; var cost=0.75 var w=’59,000’; 14 The Assignment Statement Variables are changed using the assignment statement Example: age=33; weight=150; age=weight; This means value of the right side of the = is placed in the variable on the left Read this as "age becomes 33" "weight becomes 150" "age becomes the value of weight" (or 150) 15 Assignment The universal form of assignment: <variable> <assignment symbol> <expression> For example ... day = hours/24; • value of the variable on the left is changed to have the new value of expression on right • read “=” as “is assigned” “becomes” “gets” • right-to-left value flow = is different in math and programming 16 More Assignment Flow of data is always right to left Programming is not algebra: age=17; Read: "Age becomes 17" age = age + 1; Read: "Age becomes Age + 1 (17+1 or 18)" Q:What value is now in age? (A: 18) 17 Expressions Expressions are like “formulas” saying how to manipulate existing values to compute new values, e.g. hours/24 • Operators: + - * / % produce numbers • Operators: < <= == != >= > on numbers (or strings for == and !=) produce Booleans • Operators: && || ! on Booleans produce Booleans • Grouping by parentheses is OK and smart seconds = ((days*24 + hours)*60 + min)*60 18 More Quiz Question 4: after these statements, what value is in variable writer? var writer = "Tolstoy“; var composer="Mozart“; var singer="Pavarotti"; singer=composer; writer=singer; 19 Still More Quiz Question 5: after these statements, what value is in variable x? var x=4, y=5, z=6; x=y+z; y=x; z=y+1; x=z; 20 Huh?—means another version of + Overloading Plus The + can be used to add numbers or join strings (concatenate) • • • • • • • 5 + 5 10 is the symbol for “has the value” "a" + "b" + "c" "abc" '5' + '5' '55' The operand type determines the operation Combine a number and string??? 5 + '5' '55' Rule: With an operand of each type, convert number to string, concatenate 21 First JS Program, Revisited Rewrite earlier code with variables <html><head><title>My Test Page</title></head> <body> The sum 2.0 + 2.0 equals <script language="JavaScript"> var anumber = 2.0, another, answer; another = 2.0; answer = anumber + another; document.write(answer); </script> </body> </html> 22 Demo--Greeting The following program just reads your name and displays a greeting: var name; name=prompt("Please identify yourself: "); alert("Hello, " + name + “, how are you?”); 23 Demo Dissected var name; // declare a variable called name name=prompt("Please identify yourself: "); // Asks for data and stores in name alert("Hello, " + name + “, how are you?”); // displays a message with your name in it 24 Demo2 – Guess birth year The following program just reads your name and age and displays a unique greeting based on your age: var name, age, year; name=prompt("Please identify yourself: "); age=prompt("How old are you?"); year=2006 – age; alert("Hello, " + name + ", were you born in " + year + "?"); 25 Conditional Conditionals test if an expression is true or not • General form … if (<Boolean expression>) <Then statement>; • For example if (day == "Friday") evening_plan = "party"; 26 If-Then-Else Branch both ways with If-Then-Else if (<Boolean expression>) <Then statement>; else <Else Statement>; • Example … if ((year%4)== 0) { leapYear = true; febDays = febDays+1; } else leapYear = false; 27 Demo3 – Modified Greeting The following program just reads your name and age and displays a unique greeting based on your age: var name, age; name=prompt("Please identify yourself: "); age=prompt("How old are you?"); if (age < 30) alert("Hello, " + name + ", whazzup?"); else alert("Hello, " + name + ", old chap, how do you do?"); 28 Demo3 – Notice the pattern For many programs, the sequence of statements is the same 1) Declare variables 2) Input data you need to do the calculation 3) Process the data 4) Display the answer 29 Summary Programming is the exact specification of an algorithm JavaScript is typical … with many rules Learning strategy • Do the reading first • Practicing is better than memorizing for learning the rules • Use the program-save-reload-check plan • Precision is your best friend 30 Answers (don’t peek!) Answer 1: var weight, height; Answer 2: var age=24; Answer 3: $1.50 is illegal (no $) “Rome’—can’t start “ end ‘ 42,000 should be 42000 31 Answers, cont Answer 4: after the following statements, what value is in variable writer? var writer = "Tolstoy"; ( writer becomes "Tolstoy") var composer="Mozart"; ( composer becomes "Mozart") var singer="Pavarotti"; ( singer becomes "Pavarotti") singer=composer; (singer becomes composer ("Mozart")) writer=singer; ( writer becomes singer ("Mozart")) Answer: "Mozart" 32 Answers, cont Answer 5: after the following statements, what value is in variable x? var x=4, y=5, z=6; (x gets a 4, y gets 5, z gets 6) x=y+z; ( x becomes y + z (5 +6) or 11) y=x; ( y becomes the current value of x (11)) z=y+1; (z becomes the current value of y + 1 (11 + 1) or 12) x=z; (x becomes z (12)) Answer: 12 33