410 likes | 570 Views
Iteration: Play It Again, Sam. The process of repetition: looping through a series of statements to repeatedly execute them From everyday life: digging a 3’ deep hole Decide on location for the hole, get shovel Stick shovel in dirt, scoop some out Put in yard stick… 3’ deep yet?
E N D
Iteration: Play It Again, Sam The process of repetition: looping through a series of statements to repeatedly execute them From everyday life: digging a 3’ deep hole Decide on location for the hole, get shovel Stick shovel in dirt, scoop some out Put in yard stick… 3’ deep yet? No… then repeat 2 and 3 Yes… then stop and go get a cool drink
The for Loop Basic Syntax for (<initialization>; <continuation>; <next iteration>) { <statement list>} Text that is not in metabrackets <> must be given literally The whole sequence of statements in the statement list is performed for each iteration Computer completes the whole statement sequence of the <statement list> before beginning the next iteration
The Iteration Variable Control specification: the three operations in the parentheses of the for loop Control the number of times the loop iterates Control the loop by using an iteration variable (must be declared)
The Iteration Variable (cont'd) Example: for ( j = 1 ; j <= 3 ; j = j + 1) { <statement list> } Here's what happens: The first operation is the <initialization> Sets the iteration variable's value for the first iteration of the loop. Done only once. The next operation is <continuation> Test. If the test has a false outcome, the <statement list> is skipped. If the test has a true outcome, the <statement list> is performed. When the statements are complete, the <next iteration> operation is performed Repeats with the continuation test, performs same sequence of steps.
How aforLoop Works Consider a computation on declared variablesjandtext text = "She said "; for ( j = 1; j <= 3; j = j + 1 ) { text = text + "Never! "; } alert(text);
How aforLoop Works Successive values of variabletext “She said ” before the loop “She said Never! ” after 1 iteration “She said Never! Never! ” after 2 iterations “She said Never! Never! Never! ” after 3 iterations Each time the loop body is executed, a“Never! ” is concatenated onto the initial value of variabletext
JavaScript Rules forforLoops The Iteration Variable Normal variables. Must be declared, and follow rules for variable identifiers i, j, and k are the most common choices A Starting Point Iteration can begin anywhere, including negative numbers
JavaScript Rules for for Loops (cont'd) Continuation/Termination Test Test is any expression resulting in a Boolean value Continuation must involve iteration variable to avoid infinite loop Step Size Amount of change from one iteration to the next Often called the increment or decrement
JavaScript Rules for for Loops (cont'd) Reference to the iteration variable Often used in the computation of the <statement list> Use variable j in the statement that computes 5 factorial (5!) fact = 1; for ( j = 1; j <= 5; j = j + 1 ) { fact = fact * j;}
JavaScript Rules forforLoops (cont'd) The WFI: World-Famous Iteration JavaScript uses the sameforloop statement as other programming languages, so thousands of loops with this structure are written every day: for ( j = 0; j < n; j++ ) { ...<statements> } Most frequently writtenforloop of all time We can see the iteration count immediately — it will be n times (read the limit in the test)
Avoiding Infinite Loops We (almost always) want a loop to stop looping What could go wrong? Continuation test must be based on a value that will change during the loop Must be sure to reference the correct variable in the continuation test JavaScript Rules forforLoops (cont'd)
Experiments with Flipping Coins To practiceforloops, we experiment with flipping electronic coins We can use the functionrandNum(2), which returns either 0 (tails) or 1 (heads) Set up an iteration in which our randNum() function is performed 100 times, and statistics gathered
iranges from 0 to 99, so the loop iterates 100 times (it uses the WFI) Conditional statement checks and records the outcome of random number generation When random number is 1, count of heads is increased by 1 ( heads++; ) When random number is 0, count of tails is increased by 1 ( tails++; ) Experiments with Flipping Coins (cont'd)
A Nested Loop To run several trials, consider the entire loop we just looked at as one Trial Create anotherforloop containing this Trial unit, adding a couple of needed statements We have a loop within a loop (nested loop) which causes the Trial loop (0-99) to run five times Experiments with Flipping Coins (cont'd)
A Diagram of Results To show how far off a perfect 50-50 score a trial is, display with diagram Compute the distance from 50-50 and show that number using asterisks text = text + 'Trial ' + j + ': '; for (i = 0; i < (Math.abs(heads-50)); i++) { text = text + '*'; } text = text + '\n'; alert(text); Experiments with Flipping Coins (cont'd)
Indexing Process of creating a sequence of names by associating a base name with a number (Queen Elizabeth II, Apollo 13, Superbowl XXV) Each indexed item is called an element of the base-named sequence Index Syntax index number is enclosed in square brackets[ ] Apollo[13], Superbowl[25], QE[2] Iterations can be used to refer to all elements of a name A[j]for successive iterations overjreferring to different elements ofA
Indexing (cont'd) Index Origin is the point at which indexing begins (the least index) JavaScript always uses index origin 0 (as do many other programming languages) This can be confusing, since in real life, when indexing queens, moon flights, etc., the first element usually begins with 1, or no number Queen Elizabeth, not Queen Elizabeth the zeroth
Arrays An indexed base name is called an Array Arrays must be declared var <variable> = new Array (<number of elements>) The number in parentheses gives the number of array elements Array length is the number of elements in the array var week = new Array( 7 );
Rules for Arrays Arrays are normal variables initialized bynew Array (<number of elements>) <number of elements> is number of items in array Array indexing begins at 0 Greatest index is <number of elements> -1 Number of elements is array length Index values range from 0 to length-1
Array Reference Syntax Array reference is array name together with index enclosed in brackets Index must be a non-negative integer, or an expression or variable that resolves to non-negative integer var grade = new Array(7); var k = 4; grade[k] = 87; // here, k has value 4 Grade[2] = 92; // direct use of an integer Grade[k+1] = 79; // k+1 evaluates to 5
Why the WFI is World Famous The WFI loop form is perfect to use with arrays Loop variable starts with 0, and so does array index Array declared with, say, 10 elements will have index values 0 through 9 WFI starting at 0, test with < 10, will cover each array index.
The Busy Animation Animation is simulated motion, using a sequence of still images in rapid succession JavaScript for animation: Using a timer to initiate animation events Prefetching frames of animation Redrawing web page image
Using a Timer to Initiate Animation Animations require action every 30 milliseconds (ms) Browser is idle when not working on a task Turn drawing activity into next event Timer is needed to implement online animation The Busy Animation (cont'd)
Setting a Timer setTimeout("<event handler>", <duration>) Event handler is a string giving the JavaScript computation that will run when the timer goes off Duration is any positive number of milliseconds Using a Handle to Refer to a Timer Computer uses special code called handle to identify timer Computer timers can keep track of many different times at once and can cancel the timer with the timer ID timerID = setTimeout( "animate()", 30 ); clearTimeout( timerID ); The Busy Animation (cont'd)
Using Buttons to Start/Stop the Animation Buttons can be coded to start (setTimeout()) and stop (clearTimeout()) animation <input type=“button” value=“Start” onclick=‘setTimeout(“animate()”,30’)/> <input type=“button” value=“Stop” onclick=‘clearTimeout(timerID)’/> The Busy Animation (cont'd)
Prefetching Images Graphics files used for animation are stored in separate directory Display first image To overwrite first image with the other images files in sequence, every 30 ms Image loading is generally too slow Get all images first, store them locally in an array (prefetching), then display them The Busy Animation (cont'd)
Initializing to an Image Object new Image() operation: The images are stored in an array named pics for (i = 0; i < pics.length; i++) { pics[i] = new Image(); } Using the src Component src is a field where the image's source is stored This actually displays the images on the page pics[i].src = "gifpix/Busy" + i + ".gif" The Busy Animation (cont'd)
Redrawing an Image To animate initial frame in <img src="..." />, we need to overwrite it document.images[0].src = pics[i].src; Defining the animate() Event Handler function to overwrite the image, set up for the next frame, and set timer to call itself again The Busy Animation (cont'd)
Summary Iteration, indexing, and arrays are the source of much of the power and leverage in computation; without loops, a program would be limited to executing only as many statements as we have the patience to type out in a sequence. The principles of iteration ensure that every iteration (every execution of the statement list in a loop body) contains a continuation test, and that the test is dependent on variables that change in the loop; this test determines when the loop stops cycling, preventing infinite executions.
Summary forloop basics: control part is in parentheses, loop body is in curly braces; with each iteration, the entire body is performed; the number of iterations is determined by assignments to, and tests of, the iteration variable (control part). for loop details: the initialization component in the control is executed first; prior to each iteration (including the first) the continuation predicate (control) is tested; if it is true the body is performed; if false the body is skipped and the loop ends; after each iteration, the increment operation (control) is performed.
Summary For statement is very flexible; initialization can begin with any number, continuation test can stop the loop at any number, and the increment part can increment the iteration variable by any amount (up or down) The WFI (world famous iteration) is a common pattern that initializes the iteration variable to 0, tests that it is strictly less than some limit value, and increments it by 1; the use of this pattern allows easy determination of the number of iterations (and helps with use of arrays)
Summary Indexing is where we create a series of related names by associating a number with a base name; indexed variables are called arrays; arrays must be declared like ordinary variables, but this is done with “new Array” and a length for the number of variables needed. Array elements are referenced with the array name and a non-negative index in brackets; a single array element can be used like an ordinary variable Loops and arrays are used to animate, to simulate motion by rapidly displaying a sequence of still images; pre-fetch the images and store them in an array