360 likes | 472 Views
Introduction to Programming (in JavaScript). David Stotts Computer Science Department UNC Chapel Hill. The Big Six (1) Data Storage. 0. data ( types, simple information ) 1. data storage ( variables, assignment ) 2. data retrieval ( expressions, evaluation )
E N D
Introduction to Programming(in JavaScript) David Stotts Computer Science Department UNC Chapel Hill
The Big Six(1) Data Storage 0. data (types, simple information) 1. data storage (variables, assignment) 2. data retrieval (expressions, evaluation) 3. repetition (loops) 4. decision making (conditionals) 5. procedure abstraction (functions) 6. data abstraction (arrays) 7. objects: all-the-above, wrapped up
But first… a song “You are sad,” the Knight said in an anxious tone: “Let me sing you a song to comfort you.” The name of the song is called ‘Haddocks' Eyes.’” “Oh, that's the name of the song, is it?" Alice said, trying to feel interested. “No, you don't understand,” the Knight said, looking a little vexed. “That's what the name is called. The name really is ‘The Aged Aged Man.’ ” “Then I ought to have said ‘That's what the song is called’?” Alice corrected herself. “No, you oughtn't: that's quite another thing! The song is called ‘Ways And Means’: but that's only what it's called, you know!” “Well, what is the song, then?” said Alice, by this time completely bewildered. “I was coming to that,” the Knight said. “The song really is ‘A-sitting On A Gate’: and the tune's my own invention.” Lewis Carroll, Through The Looking Glass
What’s in a name? • The White Knight gives a confusing pile of nomenclature for this song. • The song is A-sitting On a Gate • The song is calledWays and Means • The song's name is The Aged Aged Man • The song's name is calledHaddocks' Eyes • The complicated terminology distinguishing between the song, the name of the song, and what the name is called' epistemologists and linguists call the use–mention distinction. • In programming we see these issues in using symbolic names for data values and memory locations in the computer: values, variables, references, bindings, scope
1: Data Storage data storage (variables, assignment) • Data values must be stored in the computer memory for a program to operate on them • Data storage is done by the assignment statement • Assignment is putting a data value into a storage location in memory • Such a storage location used by your program is called a variable
Variables • “Variable” means the stored value can vary different values can be stored in it at different times • A variable has a text name • Example valid names x speed age trip_3 _price total$ $amount $_$ totalYearsWorked 1b2c3d4e5nnnnnnnn1j
Variables You can think of a variable as a name for a data container or box… a storage area in memory age speed title 47 -5.312 “The Island of Dr. Moreau”
Assigning to a variable How the assignment statement works age = 47 variable (LHS) assignment operator data value (RHS) read this way: variable “age” gets value 47 age 47
Assignment statement Example assignment statements age = 47 ; speed = -5.312 ; title = “The Island of Dr. Moreau” ; gearRatio_3 = 0.27 ; done = false ; Note the “;” at the end… put one at the end of every JavaScript statement
Statement put a semi-colon at the end of every JavaScript statement Cool, can do… oh, um… what is a “statement” ? A statement is the basic syntax unit from which programs are composed A program executes by going from one statement to the next and doing what each statement calls for So far all we know about are • assignment statement • alert statement ( a function call )
The Big Six(2) Data Retrieval 0. data (types, simple information ) 1. data storage (variables, assignment ) 2. data retrieval (expressions, evaluation ) 3. repetition (loops ) 4. decision making (conditionals ) 5. procedure abstraction (functions ) 6. data abstraction (arrays ) 7. objects: all-the-above, wrapped up
Detail… just go with it for now • We are looking at a lot of detail here It will seem simpler soon when we put it all together • Here at the beginning we want to emphasize the principles at work • In assignment we have these all glommed up data data storage data retrieval
2: Data Retrieval data retrieval ( expressions, evaluation ) • Once data values are stored in the computer memory we need a way to get them back for use in the program • Data retrieval is done usingexpressions andevaluation • Expressions are formulae built from variables, values, operations , expressions, ( ) • Examples: x 36 speed -77.173 age / 2.0 x – age + 3 !done “go”+“tarheels” 12.1 * (43 % 7) ((x * y) + (3 * temperature)) / ( dx - 4.325 ) done || found
Evaluating Expressions • Evaluating an expression means turning the formula into a data value • Rules define how this is systematically done • A constant evaluates to itself 5 stands for the integer value 5 • A variable evaluates to the data value stored in its memory location x x now stands for the number value 17.3 17.3
Evaluating Expressions • A complex expression is evaluated by firstevaluating the simple parts, thencombining the values using the operations dx dy • dx + dy evaluates to 17.3 + 20.514 then 37.814 • total = dx + dy causes this memory state: • total 17.3 20.514 37.814
Operator Order Matters 2011, big Internet argument over this What is 48/2(9+3) ? Answer depends on order of evaluation Also on how we handle the implied multiplication Is it 48/(2*(9+3))… or 48/24 … or 2 Is it 48/2*(9+3) and we use P E MD AS ? 48/2*12 … or 24*12 … or 288
Big Names Can Differ let’s try Google and then JavaScript
Be Explicit to be Sure • JavaScript has no implied multiplication • No implied anything in expressions • Must put in all operators • Put parentheses in liberally just to be sure you get the program to do what you intend • Lots of parentheses don’t cause “extra work” but they do cause extra clarity
ok… More Programming • Now we can go back to our first program and make some changes… our second program varyears; // variable declaration varmonths; // variable declaration years = 42; // assignment months = years*12; // expression evaluation //and assignment alert(“If a person is age " + years); alert("In months, this is " + months); alert(years + " years is " + months + " months");
Rules? Do we need no stinkin’ rules? • Your author laments all the prior programming instructors who insisted on lots of rules • Says they limit the natural awe and wonder of students who are having their captive minds freed by programming ... • While I am overall sympathetic to the point, we do have somerules here • They are for your own comfort and safety… like “keep head and hands inside the vehicle while the train is in motion”… and ...
RULE: Declare your variables ! • Declare your variables ! • Declare your variables ! no, srsly … declare your variables
JS Hints and Helps JavaScript allows undeclared variables, but they can cause (quietly) executions errors error console Open this up to see compile and run messages Firefox: find it in the “web developer” menu “use strict”; put this as the first line in your program put it exactly, quotes and all gives error message if variable is undeclared
More Expressionsfunctions on native types Some operations convert values of one type into value of a different type alert( “message” ) a popup box Number(“25.4”) 25.4 negative(-73) true Some operations convert values of one type into different values of the same type floor(5.2) 5
Functions We call these functions A name, some arguments inside parentheses Number(“25.4”) length(“abc”) negative(73) myFunc( -12, ”no”, 3.14159 ) When you see a function name with argument values you expect it to run and produce a result value
Functions: Dot Notation Sometimes we will see a function invoked via “dot notation” var line = “12.75” ; line.length 5 line.parseInt() 12.75 (a number, not a string) This will be more prominent later in the course
Function Calls are Expressions A function name with argument values is referred to as a function call A function call produces a value (so does an expression) So a function call can appear as a part of an expression months = 12 * Number(“47”); miles = Math.floor(time*speed) + init;
Well Done • You began the “big six” concepts with 0. Data numbers, booleans, strings operators that work on each type • You saw 1. Data Storage variables and assignment • You saw 2. Data Retrieval expressions and evaluation • You saw function calls as expressions • You wrote another program • and… Rule 1: declare your variables!
For Next Time • Finish reading chapter 1 in the text • Practice with the programs on the web site… add stuff to them, try things and see what happens • Take a look at the HTML tags document under “Resources” on the class web page • Maybe try to spice up the web page part of your practice program(s)
Simulated Execution • One way to understand how your programs work is to “play computer” • To do this we will draw a diagram to represent the computer memory, with variable names on the memory slots. • Go through your program, line by line, in the order the computer will execute them • Mark on the memory diagram each change the program makes to stored values (assignments)
Simulated Execution Demo the technique on the whiteboard or document camera Remember that a variable starts out with no value in it until some assignment happens In the CPU: line “expression evaluation” 504 42 * 12 42 42 years assignment 504 months assignment
Yet More Programming • Our third program: getting input from the user varyears; varmonths; years = prompt("Age of the person (in years)?"); months = years * 12 ; alert("The person is age " + years); alert("In months, this is " + months); alert(years+" years is "+months+" months")
Input: prompt • There are several ways to do I/O in a Javascript program. One input way is the prompt operation syntax: someVar = prompt ( string ); • The string is printed in a popup box and the user is given a text field into which to type a value • The value the user types is assigned to someVar • Warning: prompt gets text from the user (a string), since text is what keyboard typing generates • If you want a number from the user, you must make sure the text gets converted properly
Input: safe prompt • To get number input from a user someVar = Number( prompt ( string ) ); • The Number function makes a numeric data item out of the text the user types (think Haddock’s Eyes here) • “127” is text, just like “UNC” is text, and it makes no sense to add, divide, etc. on it • 127 is an integer number, and it makes sense to add, subtract, divide, etc. on it • Difference is in the internal storage formats
Well Done • You know what a variable is, and how to establish one in a JavaScript program • You know how to store data into a variable with the assignmentstatement • You know how to retrieve data stored in a variable using expressions and evaluation • You know how to simulate execution of your program using a memory diagram • You know how to do I/O in Javascript using prompt (for input) and alert (for output) and how to convert text into numbers