Chapter 20 Iteration Principles. Learning Objectives Trace the execution of a given for loop Write a World-Famous Iteration for loop Discuss the structure.

Slides:



Advertisements
Similar presentations
Java Script Session1 INTRODUCTION.
Advertisements

Programming with Microsoft Visual Basic th Edition
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.
The Web Warrior Guide to Web Design Technologies
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
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.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven.
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.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Introduction to JavaScript for Python Programmers
Programming Games Computer science big ideas. Computer Science jargon. Show virtual dog Homework: [Catch up: dice game, credit card or other form.] Plan.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
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.
Chapter Three The UNIX Editors. 2 Lesson A The vi Editor.
Chapter 12: How Long Can This Go On?
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
CPS120 Introduction to Computer Science Iteration (Looping)
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 5: Windows and Frames
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 6: The Repetition Structure
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
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.
Learning Objectives State and apply the Decomposition Principle
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
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.
Chapter Three The UNIX Editors.
JavaScript, Fourth Edition
ActionScript: For Loops, While Loops, Concatenation and Arrays MMP 220 Multimedia Programming This material was prepared for students in MMP220 Multimedia.
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 © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
IS2802 Introduction to Multimedia Applications for Business Lecture 4: JavaScript, Loops, and Conditional Statements Rob Gleasure
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
JavaScript, Sixth Edition
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Loops and Arrays Chapter 19 and Material Adapted from Fluency Text book.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Fluency with Information Technology
Topics Introduction to Repetition Structures
Chapter 19 and Material Adapted from Fluency Text book
CIS 16 Application Development Programming with Visual Basic
Javascript Arrays.
Tutorial 10: Programming with javascript
The Smooth Motion: Case Study in Algorithmic Solving
Presentation transcript:

Chapter 20 Iteration Principles

Learning Objectives Trace the execution of a given for loop Write a World-Famous Iteration for loop Discuss the structure of nested loops Explain the use of indexes List the rules for arrays; describe the syntax of an array reference Explain the main programming tasks for online animations

Terminology Repeat –5 repeats, means you may have done it once followed by 5 more times (the repeats!) Iterate –5 iterations means that you do it 5 times Iteration means looping through a series of statements to repeat them In JavaScript, the main iteration statement is the for loop

for Loop Syntax for ( ; ; ) { } Text that is not in must be given literally The statement sequence to be repeated is in the

for Loop Syntax for ( ; ; ) { } The whole statement sequence is performed for each iteration The computer completes the whole statement sequence of the before beginning the next iteration

for Loop Syntax for ( ; ; ) { } Three operations in the parentheses of the for loop control the number of times the loop iterates Called the control specification

for Loop Syntax for ( ; ; ) { } sets the iteration variable’s value for the first (if any) iteration of the loop

for Loop Syntax for ( ; ; ) { } has the same form as the predicate in a conditional statement If the test has a false outcome, the loop terminates and is skipped

for Loop Syntax for ( ; ; ) { } If has a true outcome, the is performed When the statements are completed, the operation is performed changes iteration variable

for Loop Syntax for ( ; ; ) { } Next iteration starts with the test, performing the same sequence of operations Iterations proceed until the test has a false outcome, terminating the loop

for Loop

for Sequence

for Example

WFI! World-Famous Iteration (WFI) JavaScript uses the same for loop statement structure as other popular programming languages like Java, C++, and C Using the form just described for (var j=0; j<n; j++) {... }

Iteration Variables Iteration variables (j here) are normal variables following the normal rules Programmers tend to choose short or even single-letter identifiers for iteration i, j, and k are the most common They must be declared in the same way as other identifiers Declaring in the loop is allowed and common

Starting Point WFI begins at 0 Generally, for loops may begin anywhere Starting at zero simplifies using loops WFI may use any iteration variable name

Continuation/Termination Test The WFI continuation is j < n The n can be any number, including a numeric expression While the continuation can be any boolean test, j < n is often used

Next! The WFI next iteration increases the iteration variable by one j = j + 1 works just fine j++ is a common shorthand In general ‒ Any change of the index variable is allowed ‒ Other choices create more complexity

Iteration Variable does Math! The iteration variable is often used in computations in the

Why is WFI Famous? Number of iterations is easy to find: it’s just n Simple. ‒ Would you rather figure out for(var foo = -5; foo >= -27; foo -= 2) {... } WFI iteration variable takes on 0 through n-1 Sometimes you need 1 through n, but adding 1 is no big deal

Infinite Loops ad infinitum The fifth property of algorithms is that they must be finite: always stop and report a result, or that none is possible Every for loop has a continuation test, so it can stop But it is still possible to fumble the test, and create an infinite loop

Infinite Loops ad infinitum for (var j = 0 ; j < 3; i = i + 1) {... } The incremented variable is not in the continuation test (Note i and j) The loop, then, will never end Easy error to make ‒ Imagine incomplete change ‒ Perhaps after a copy

for Loop Practice: Heads/Tails Let’s use randNum(2) from Chapter 19 –It will return 0 (tails) or 1 (heads) And flip a “coin” 100 times Use WFI Wrap the test loop in a function Use another loop to make multiple tests by repeatedly calling the function

A Diagram of Results Display a row of asterisks showing the variation from 50/50 Display the trial numbers from 1: ‒ outAns = outAns + “Trial “ + (j+1) + “: “; ‒ Notice that + has two different meanings here. The code uses a nested loop: The of one contains another

A Diagram of Results

Nested Loops…Loop in a Loop All programming languages allow loops to nest Inner and outer loops must use different iteration variables or else they will interfere with each other

Indexing Indexing is the process of creating a sequence of names by associating a base name with a number ‒ Chapter 20; Toy Story 3 Each indexed item is called an element of the base-named sequence An index is enclosed in [square brackets] in JavaScript

Arrays [1] In programming, an indexed base name is called an array Arrays must be declared In JavaScript, arrays are declared: var = new Array( ) Notice that Array starts with an uppercase “A”

Arrays [2] Variables either are or are not arrays var week = new Array(7); –week is the identifier being declared, –new Array(7) specifies that the identifier will be an array variable. –number in parentheses gives the number of array elements To refer to an array’s length, we use.length

Arrays [3] Rules for arrays in JavaScript: –Arrays are normal variables initialized by new Array( ) – in the declaration is just that—the number of array elements –Array indexing begins at 0 –Number of elements in an array is its length –Greatest index of an array is − 1 (because the origin is 0)

Arrays [4] An array reference consists of array name with an index [enclosed in brackets] Value to which the index evaluates must be less than the array’s length Example: –var dwarf = new Array(7); –dwarf[0] = "Happy"; –dwarf[1] = "Sleepy"; The number in the bracket is called the subscript

Indexing Example

WFI and Arrays for(var j = 0; j < n; j++) { … j … } 0-origin of the WFI is perfect for 0-origin indexing Loop limit n is the size of the array Iteration variable goes through exactly all legal index values

WFI and Arrays

Magic Decider

Create an array of messages to display Make a button showing the 8-ball image Clicking on the 8-ball creates an onclick event to which our program responds The program chooses a message at random and displays it Display is accomplished by changing the Document Object Model

Animation Movies, cartoons, etc. animate by the rapid display of many still pictures known as frames Human visual perception is relatively slow so it’s fooled into observing smooth motion when the display rate is about 30 fps or 30 Hz Iteration, arrays, and indexing can be used for animation

JavaScript Animation Animation in JavaScript requires three things: 1.Using a timer to initiate animation events 2.Prefetching the frames of the animation 3.Redrawing a Web page image

1. Using a Timer JavaScript animation will be shown in a Web browser. Web browsers are event driven: –They sit idle until an event occurs, then they act, and then idly wait for next event…repeat Animation requires requires action every 30 milliseconds So, turn the activity of drawing the next frame into an event!

1. Using a Timer Programmers’ timers typically “tick” once per millisecond Timers, in JavaScript, are intuitive The command to set a timer is setTimeout (" ", )

1. Using a Timer is a “string” giving the JavaScript computation that runs when the timer goes off is positive number in milliseconds saying how long until the timer should go off the last step for the function must be to set the timer so that it “wakes up” again or the animation will stop

1. Using a Timer Example: –To display a frame in 30 ms using the function animate( ): setTimeout("animate( )", 30) 30 ms later the computer runs the animate( ) function and displays the frame

1. Using a Timer Using a Handle to Refer to a Timer –Computer timers can keep track of many different times at once –Computers use a special value called a handle to identify which timer is being used timerID is the variable name to handle our timer timerID = setTimeout( "animate()", 30 ); To cancel our timer: clearTimeout( timerID );

1. Using a Timer Using Buttons to Start/Stop the Animation –Buttons can be used to start (setTimeout()) and stop (clearTimeout()) animation Start button starts the timer initially Animation keeps going on its own Stop button clears the timer to stop it

2. Prefetching Graphics files are usually stored in a directory gifpix Display first image at first (doesn’t need to be animated yet)

2. Prefetching To animate (overwrite image with next sequenced image): –Loading an image one-at-a-time is too slow –Get all images first, store them locally, then display them Images are already numbered (to keep track of where they are in the sequence) –Indexed already? use an array!

2. Prefetching Initializing to an Image Object: –Elements of the array must be initialized to an image object –Image object is a blank instance of an image –Initialize the 12 array elements to image objects requires an iteration and the new Image() operation:

2. Prefetching Using the src Component –Field called src where the image’s location is stored – tag in HTML –This assignment pre-fetches the image –Browser saves the name, gets the file, stores it in memory

2. Prefetching Important difference between the prefetching and using –Prefetching: is not visible on the screen – : is visible on the screen Advantage to use both: there is an initial image to be seen, then the animation occurs

2. Prefetching Use a loop to pre-fetch all the images Note how the file name is computed using the iteration variable

3. Redrawing an Image To animate we need to overwrite the image with prefetched ones Browsers keep an array of the images used on the page in the DOM When is encountered, browser fills its images To change initial frame, write:

3. Redrawing an Image Defining the animate( ) event Handler –To animate the Busy icon we must cycle through each of the i values, one every 100 ms –animate( ) event handler overwrites the image, sets up for the next frame, and sets the timer to call itself again:

Complete Busy Animation

Three Key Ideas Saving state: The app needs to remember which picture to display next Prefetching: Just as the Busy Animation prefetched images and stored them locally so they could be displayed rapidly, the RPS app does the same Changing document.images: We used an array known as document.images

Rock, Paper Scissors Also uses timed events and changes images

Summary The basics of for loop iteration. The control part of a for statement is written in parentheses and the is enclosed in curly braces. With each iteration, the entire statement list is performed –The number of iterations is determined by assignments to, and tests of, the iteration variable as specified in the control part

Summary In the JavaScript for statement, the component is executed first –Then, prior to each iteration, including the first, the predicate is tested –If it is true, the is performed; otherwise, it is skipped, and the for statement terminates –After each iteration, the operation is performed

Summary The principles of iteration ensure that every iteration contains a test and that the test is dependent on variables that change in the loop The for statement is very flexible. The can begin with any number, the test can stop the loop at any number, and the operation can increment by various amounts upward or downward

Summary Programmers routinely use the World-Famous Iteration (WFI), a stylized iteration that begins at 0, tests that the iteration variable is strictly less than some limit, and increments by 1 –There is no obligation to use the WFI, but it allows us to determine the number of times around the loop quickly –Because it is common to make errors figuring out the number of iterations, programmers use the WFI to recognize the number of iterations quickly

Summary In indexing, we create a series of names by associating a number with a base name –If we need more names, we count more numbers –Indexed variables are known as arrays in programming –Like ordinary variables, arrays must be declared, but they use the new Array( ) syntax, in which is the number of elements of the array

Summary Array elements—referenced by giving the name and a non-negative index in brackets—can be used like ordinary variables. Arrays and iterations can be effectively used together The basic concepts of online animation –All animations achieve the appearance of motion by rapidly displaying a series of still frames

Summary When animating information displayed by a Web browser, we should prefetch the images so that they are readily accessible for rapid display –The key idea is to use a timer to create events, and then use the timer event handler to redraw an image that has been placed on the Web page by the tag –These are referenced as the elements of the document’s images array