290 likes | 454 Views
Introduction to Programming (in JavaScript). David Stotts Computer Science Department UNC Chapel Hill. The Big Six (3) Repetition. 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(3) Repetition 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 brief asideIncrement, Decrement, Shortcuts • 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++ This form appears in loops often
but first… a brief asideIncrement, Decrement, Shortcuts • 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 – numvariable upper -= num upper = upper / 2
3: Repetition 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 “
Here are some calculations var first_num; // variable declaration var second_num; // variable declaration vartotal; // 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
What if … 3 times ? Cut and paste the code? var first_num; // variable declaration var second_num; // variable declaration vartotal; // 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); It works, but … is it good?
What if … lots ? var first_num; // variable declaration var second_num; // variable declaration vartotal; // 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); 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
A Better Way: Loop Syntax 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 )
Definite Loop 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 example Spruce the train For // definite condition ( 11 times, one per car ) repeat { // body actions wash car windows grease wheel axles touch up car paint }
Definite Loop Human task example Spruce the train For start with car 1 stop after car 11 repeat { // body actions wash car windows grease wheel axles touch up car paint move to next car } Work with a sequence “for” loops are a lot like this
Definite Loop Form 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 )
“For Loop” Example real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration vartotal; // 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); } stop Move to next time start
“For Loop” Example Need to do this 500,000 times? var first_num; // variable declaration var second_num; // variable declaration vartotal; // 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); } stop
Indefinite Loop Human task example Cut the Iron Bar while // indefinite condition (hot iron bar is one piece) repeat { // body actions heat bar red hot raise the hammer smack the chisel } How many hammer hits will it take? Who knows…
Indefinite Loop Form 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 )
“While Loop” Example real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration vartotal; // variable declaration var 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? "); } Loop another time? Extra code does “Move to next” condition
“While Loop” Example real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration vartotal; // variable declaration var 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
Loop Summary In general … for loop: definite, specific # iterations while loop: indefinite, unknown # iterations • loop until user says “I’m done” • loop until data says “It’s done”
Counters, Accumulators • 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 x = x + 1
“For Loop” Counter Example var max; varkount = 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); A counter MUST be initialized outside the loop, before the loop is entered and executed
Counters, Accumulators • 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
“For Loop” Accumulator Example var max; varfact = 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); A multiply accumulator is initialized to 1 (why?)
“For Loop” Accumulator Example varn; vartotal = 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); An add accumulator is initialized to 0 (why?)