Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Iteration Principles Once is Not Enough lawrence snyder c h a p t e r 21.

Slides:



Advertisements
Similar presentations
Programming with Microsoft Visual Basic th Edition
Advertisements

Chapter 20 Iteration Principles. Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Learning Objectives Trace the execution.
Chapter 20 Iteration Principles. Learning Objectives Trace the execution of a given for loop Write a World-Famous Iteration for loop Discuss the structure.
Programming Logic and Design, Third Edition Comprehensive
Repeating Actions While and For Loops
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 20 Thinking Big: Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Anatomy of a Function Functions are packages for.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Copyright © Texas Education Agency, Computer Programming For Loops.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Programming Games Computer science big ideas. Computer Science jargon. Show virtual dog Homework: [Catch up: dice game, credit card or other form.] Plan.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
 Section Voting is up  Vote in your section by Thursday, 10pm  Assignment: 20 pts for voting  Two labs this week:  Web App Design Lab  Coin Flipping.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 20 Iteration Principles. Learning Objectives Trace the execution of a given for loop Write a World-Famous Iteration for loop Discuss the structure.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Announcements Assignment 9 is due Project 2 is due 7/27/04 We will be skipping chapter 22 Test 3 (chapters 18-21) will be on 7/29/04 Tip of the Day : Functions.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
CPS120 Introduction to Computer Science Iteration (Looping)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
DHTML AND JAVASCRIPT Genetic Computer School LESSON 5 INTRODUCTION JAVASCRIPT G H E F.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Conditional Execution
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
6 Chapter 61 Looping Programming Logic and Design, Second Edition, Comprehensive 6.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 22 The Smooth Motion: Case Study in Algorithmic Solving.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Today’s Announcements Assignment 8 is due Project 2 is due 7/27/04 We will be skipping chapter 22 Test 3 (chapters 18-21) will be on 7/29/04 Tip of the.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
JavaScript, Fourth Edition
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Announcements CLUE Tutoring Wednesday nights 7-8:30PM MGH extra-credit points for each session you attend from last week through the end of the quarter.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
COMP Loop Statements Yi Hong May 21, 2015.
Tutorial 11 1 JavaScript Operators and Expressions.
Concepts of Algorithmic Thinking Iterations, or Loops Once is not Enough D.A. Clements, Lecturer Information School 2/23/2016 D.A. Clements, MLIS, UW Information.
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
JavaScript, Sixth Edition
Loops and Arrays Chapter 19 and Material Adapted from Fluency Text book.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Fluency with Information Technology
ECS10 10/10
JavaScript: Functions.
Chapter 19 and Material Adapted from Fluency Text book
Arrays, For loop While loop Do while loop
Doing things more than once
The Smooth Motion: Case Study in Algorithmic Solving
Presentation transcript:

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Iteration Principles Once is Not Enough lawrence snyder c h a p t e r 21

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-2 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 1)Decide on location for the hole, get shovel 2)Stick shovel in dirt, scoop some out 3)Put in yard stick… 3’ deep yet? 4)No… then repeat 2 and 3 5)Yes… then stop and go get a cool drink

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-3 The for Loop Basic Syntax for ( ; ; ) { } 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 before beginning the next iteration

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-4 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-5 The Iteration Variable (cont'd) Example: for ( j = 1 ; j <= 3 ; j = j + 1) { } Here's what happens: –The first operation is the Sets the iteration variable's value for the first iteration of the loop. Done only once. –The next operation is Test. If the test has a false outcome, the is skipped. If the test has a true outcome, the is performed. When the statements are complete, the – operation is performed Repeats with the continuation test, performs same sequence of steps.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-6

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-7 How a for Loop Works Consider a computation on declared variables j and text text = "She said "; for ( j = 1; j <= 3; j = j + 1 ) { text = text + "Never! "; } alert(text);

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-8 How a for Loop Works Successive values of variable text “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 variable text

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-9

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JavaScript Rules for 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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JavaScript Rules for for Loops (cont'd) Reference to the iteration variable –Often used in the computation of the –Use variable j in the statement that computes 5 factorial (5!) fact = 1; for ( j = 1; j <= 5; j = j + 1 ) { fact = fact * j; }

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley JavaScript Rules for for Loops (cont'd) The WFI: World-Famous Iteration –JavaScript 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 } –Most frequently written for loop of all time –We can see the iteration count immediately — it will be n times (read the limit in the test)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 for for Loops (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Experiments with Flipping Coins To practice for loops, we experiment with flipping electronic coins We can use the function randNum(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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Experiments with Flipping Coins (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley i ranges 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 Experiments with Flipping Coins (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Experiments with Flipping Coins (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Diagram of Results –To show how far off a perfect score a trial is, display with diagram –Compute the distance from 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Experiments with Flipping Coins (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-22

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 over j referring to different elements of A

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays An indexed base name is called an Array –Arrays must be declared var = new Array ( ) –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 );

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rules for Arrays Arrays are normal variables initialized by new Array ( ) is number of items in array Array indexing begins at 0 Greatest index is -1 Number of elements is array length Index values range from 0 to length-1

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Busy Animation (cont'd)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Setting a Timer setTimeout(" ", ) –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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Redrawing an Image –To animate initial frame in, 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21-37

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary for loop 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.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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