David Stotts Computer Science Department UNC Chapel Hill Introduction to Programming (in JavaScript)
Mar 22, 2016
David StottsComputer Science Department
UNC Chapel Hill
Introduction to Programming
(in JavaScript)
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
The Big Six(3) Repetition
Often we need to “bump up” a variable value… add a little to what’s stored there
The pattern is to have the same variable name on both LHS and RHS of assignment
Here variable is “incremented” by 1 (all forms mean the same thing)
x = x + 1 x += 1 x++
but first… a brief asideIncrement, Decrement, Shortcuts
This form appears in loops often
We can increment by more than 1’s x = x+2 x += 2 age = age+9 age += 9
We can increment by some variable amount, it doesn’t have to be just constants
distance = distance + currMiles speed = speed + (time*accel) speed += time*accel
but first… a brief asideIncrement, Decrement, Shortcuts
We can use more than just “+”(although the word “increment” is usually used for bumping up with addition) speed = speed * 2 speed *= 2
factorial = factorial * num factorial *= num
but first… a brief asideIncrement, Decrement, Shortcuts
We can bump down a variable… decrement
max = max – 1 max -= 1 one max--
highend = highend – 10 constant highend -= 10
upper = upper – num variable upper -= num upper = upper / 2
but first… a brief asideIncrement, Decrement, Shortcuts
Repetition (loops) Often we have a set of operations we would
like to repeat over and over We do this with loops (iteration)
World’s most famous loop:
“ lather, rinse, repeat “
3: Repetition
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declaration
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
What if we want to repeat this a few times?Perhaps the user has more than one
number pair to add
Here are some calculations
Cut and paste the code?var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declaration
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
What if … 3 times ?
It works, but … is it good?
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declaration
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
first_num = Number(prompt(“First number? "));second_num = Number(prompt(“Second number? “));total = first_num + second_num;alert(“Their sum is “ + total);
What if … lots ? 10 repetitions !!
What if we need 100?500,000 ?
What if we want to repeat until the user is tired of it, or out of data? How many times will that be?
Cut and paste on code lines clearly does not scale well
In a loop the syntax specifies two important components the collection of program statements
we want to repeat ( the loop body )
how many times to repeat the collection ( the number of iterations )
A Better Way: Loop Syntax
How to create a 20 tulip bouquet
repeat // number of iterations 20 times all these steps { // body cut a tulip trim to proper length put it in the vase arrange to a pleasing look}
Definite Loop
Human task exampleSpruce the trainFor // definite condition ( 11 times, one per car )repeat { // body actions wash car windows grease wheel axles touch up car paint}
Definite Loop
Human task exampleSpruce the trainFor start with car 1 stop after car 11repeat { // body actions wash car windows grease wheel axles touch up car paint move to next car}
Definite Loop
“for” loops are a lot like this
Work with a sequence
Definite loop: specific number of times, like counting items in a collection
Concept for (N times) { do all these body statements}
where N is some specific number
( this is NOT quite JavaScript syntax )
Definite Loop Form
real JavaScript syntax
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declaration
for (var i=1; i<=3; i++) { // says “do 3 times”
// loop body is between the “curly braces” first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total);}
“For Loop” Example
startstop Move to next
time
Need to do this 500,000 times?
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declaration
// user should get a cup of coffee and settle in …// here comes a LOT of data input typing
for (var i=1; i<=500000; i++) { first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total);}
“For Loop” Example
stop
Human task exampleCut the Iron Barwhile // indefinite condition (hot iron bar is one piece)repeat { // body actions heat bar red hot raise the hammer smack the chisel }
Indefinite Loop
How many hammer hits will it take? Who knows…
Indefinite loop: repeat the loop body an unpredictable number of times
Concept
while ( some condition holds ) { do all these body statements } ( this is NOT quite JavaScript syntax )
Indefinite Loop Form
real JavaScript syntax
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declarationvar more_input = “yes” ; // variable declaration
while( more_input == “yes” ) { // loop body is between the “curly braces” first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); more_input = prompt(“do again? ");}
“While Loop” Example
Loop another time?
Extra code does “Move to next” condition
real JavaScript syntax
var first_num; // variable declarationvar second_num; // variable declarationvar total; // variable declarationvar more_input = “yes” ; // variable declaration
while( more_input == “yes” ) { first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); more_input = prompt(“do again? ");} User says “I’m done… let’s stop looping”
“While Loop” Example
real JavaScript syntax
var target;var counter = 2;var fact = 1;
target = Number(prompt(“what number ?”));
while ( counter <= target ) { fact = fact * counter; counter = counter + 1;}alert(target + “ factorial is ” + fact);
Data says “It’s done… stop the loop” not a user input, an internal variable change
“While Loop” Example
In general …
for loop: definite, specific # iterationswhile loop: indefinite, unknown # iterations
◦ loop until user says “I’m done”◦ loop until data says “It’s done”
Loop Summary
Counter and Accumulator are common patterns of variable use
Remember the increment concept (or decrement) from earlier?
A counter is an increment inside a loop ◦we usually increment by 1 (count by 1’s) but
not always
Counters, Accumulators
x = x + 1
var max; var kount = 0; // variable declaration // AND initialization combined
max = Number(prompt(“what upper limit?”));
for (var i=1; i<=max; i++) { kount = kount + 1; } alert(“we counted to “ + kount);
“For Loop” Counter Example
A counter MUST be initialized outside the loop, before the loop is entered and executed
Accumulator : generalized counter a counter in a loop is incremented by a
variable amount An accumulator is used to build a result
incrementally -- one piece at a time◦ we “grow” the result value some every time we execute
the body of the loop result = result + i*offset factorial = factorial * num factorial *= num
Counters, Accumulators
var max; var fact = 1; // variable declaration // AND initialization combined
max = Number(prompt(“factorial of what?”));
for (var i=1; i<=max; i++) { fact = fact * i; } alert(max + “ factorial is “ + fact);
“For Loop” Accumulator Example
A multiply accumulator is initialized to 1 (why?)
var n; var total = 0; // variable declaration // AND initialization combined
for (var i=1; i<=5; i++) { n = Number(prompt(“gimme a num”)); total = total + num; } alert(“5 user inputs sum to “ + total);
“For Loop” Accumulator Example
An add accumulator is initialized to 0 (why?)