Chapter 21 Once Is Not Enough Iteration Principles
- Slides: 35
Chapter 21: Once Is Not Enough: Iteration Principles Fluency with Information Technology Third Edition by Lawrence Snyder Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Iteration: Play It Again, Sam • The process of repetition: looping through a series of statements to repeat them 1 -2 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2
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 1 -3 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3
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) 1 -4 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4
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. Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1 -5 5
1 -6 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6
How a for Loop Works • Consider a computation on declared variables j and text = "She said "; for ( j = 1; j <= 3; j = j + 1 ) { text = text + "Never! "; } alert(text); 1 -7 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7
1 -8 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8
Java. Script Rules for Loops • 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 1 -9 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9
Java. Script Rules 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 1 -10 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10
Java. Script Rules 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; } 1 -11 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11
Java. Script Rules for Loops (cont'd) • The World-Famous Iteration – Java. Script uses the same for loop statement as other programming languages, so thousands of loops with this structure are written every day: for ( j = 0; j < n; j++ ) {…} – Most frequently written for loop of all time – We can see the iteration count immediately — it will be n times 1 -12 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12
Java. Script Rules for Loops (cont'd) • Avoiding Infinite Loops • 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 1 -13 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13
Experiments with Flipping Coins • To practice for loops, we experiment with flipping electronic coins • We can use the function rand. Num(2), which returns either 0 (tails) or 1 (heads) • Set up an iteration in which our rand. Num() function is performed 100 times, and statistics gathered 1 -14 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14
Experiments with Flipping Coins (cont'd) 1 -15 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15
Experiments with Flipping Coins (cont'd) • i ranges from 0 to 99, so the loop iterates 100 times • 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++; ) 1 -16 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16
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 another for loop 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 1 -17 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17
Experiments with Flipping Coins (cont'd) 1 -18 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18
Experiments with Flipping Coins (cont'd) • A Diagram of Results – To show 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); 1 -19 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19
Experiments with Flipping Coins (cont'd) 1 -20 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20
1 -21 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21
Indexing • Process of creating a sequence of names by associating a base name with a number (like Apollo 13) – Each indexed item is called an element of the base-named sequence • Index Syntax – index number is enclosed in square brackets [ ] • Iterations can be used to refer to all elements of a name – A[j] for successive iterations over j referring to different elements of A 1 -22 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 22
Indexing (cont'd) • Index Origin – The point at which indexing begins (the least index) – In life, the first element may begin with 1, or have no number (Queen Elizabeth) – Java. Script always uses index origin 0 1 -23 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23
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 ); 1 -24 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24
Rules for Arrays • Arrays are normal variables initialized by new 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 1 -25 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25
Array Reference Syntax • Array reference is array name together with index enclosed in brackets (non-negative integer or expression or variable that resolves to non-negative integer) array[i] • 0 -origin loop iteration is perfect for arrays 1 -26 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 26
The Busy Animation • Java. Script animation: – Using a timer to initiate animation events – Prefetching frames of animation – Redrawing web page image 1 -27 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 27
The Busy Animation (cont'd) 1 -28 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28
The Busy Animation (cont'd) • 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 1 -29 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29
The Busy Animation (cont'd) • Setting a Timer set. Timeout("<event handler>", <duration>) – Event handler is a string giving the Java. Script 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 cancel the timer with the timer ID timer. ID = set. Timeout( "animate()", 30 ); clear. Timeout( timer. ID ); 1 -30 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 30
The Busy Animation (cont'd) • Using Buttons to Start/Stop the Animation – Buttons can be coded to start (set. Timeout()) and stop (clear. Timeout()) animation 1 -31 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31
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 1 -32 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32
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" 1 -33 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33
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 1 -34 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34
1 -35 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35
- Much vs many
- Our failing schools enough is enough summary
- And doggone it i'm good enough
- Our failing schools enough is enough summary
- Security is always too much until the day it is not enough
- Learning is not enough we must apply
- Not enough nelsons.com
- Not enough grammar
- Sadlier level d unit 1 synonyms
- Why is it not advisable to pursue many strategies at once
- Inversion with negative adverbs
- Secant method شرح
- Iteration demo
- Solve the recurrence relation
- Recursion vs iteration
- Sequence iteration selection
- Value iteration
- Value iteration
- Orthogonal iteration
- Alan fern
- Markov decision process
- What is the purpose of an iteration recap?
- Iterating in math
- What is iteration in computer science
- Recursion
- Iteration definition computer science
- Which statement is true about iteration goals
- Successive approximation method in numerical methods
- Lambda iteration
- Final iteration definition
- Similarities between iteration and recursion
- Value iteration
- Value iteration
- Lanczos iteration
- What is embarrassingly parallel
- Iteration abstraction