Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fluency with Information Technology

Similar presentations


Presentation on theme: "Fluency with Information Technology"— Presentation transcript:

1 Fluency with Information Technology
7th Edition Chapter 20 Iteration Principles

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

3 Repeat Versus Iterate Repeat: When something is repeated multiple times, it has been done once, followed by the number of repetitions Repeated 5 times = Done 6 times total: once, with 5 repeats Iterate: Performing an operation multiple times 5 iterations = Done 5 times total

4 1.1 JavaScript's Main Iteration: The for loop
JavaScript for loop syntax: for (<initialization>; <continuation>; <next iteration>) { <statement list>; } Text that is not in <meta-brackets> must be given literally The statement sequence to be repeated is in the <statement list> The whole statement sequence is performed for each iteration The computer completes the whole statement sequence of the <statement list> before beginning the next iteration

5 The for Loop: Control Specification
The three operations in the parentheses of the for loop control the number of times the loop iterates: <initialization> <continuation> <next iteration>

6 Loop Control: Initialization and Continuation
<initialization> sets the iteration variable’s value for the first (if any) iteration of the loop <continuation> is a test: If it has a false outcome, the loop terminates and the <statement list> is skipped If it has a true outcome, the <statement list> is performed When the statements are completed, the <next iteration> operation is performed

7 Loop Control: Next Iteration
<next iteration> increments the iteration variable (changes it) Starts with the <continuation> test, performing the same sequence of operations Iterations proceed until the <continuation> test has a false outcome, terminating the loop

8 Table 20.1 Operations on j: for (j = 0; j < 3; j = j+1)
Operation Result Role j = 0 j's value is 0 Initialize iteration variable j < 3 true; j is less than 3 First <continuation> test, do statements, continue j = j + 1 j's value is 1 First <next iteration> operation Second <continuation> test, do statements, continue j's value is 2 Second <next iteration> operation Third <continuation> test, do statements, continue Third <next iteration> operation false; j is equal to 3 Fourth <continuation> test, terminate

9 A for Loop Scratchpad Example
var text = "She said, "; for (var j = 0; j < 3; j = j + 1) { text = text +"Never! "; } text /* She said, Never! Never! Never!

10 1.2 World Famous Iteration (WFI)
As the name suggests, the WFI requires 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

11 1.2 World Famous Iteration (WFI): Iteration Variable
As the name suggests, the WFI requires iteration variables (a way to keep track of what step in the loop the statements are being executed): 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

12 Initializing the WFI WFI begins at 0 (not 1)
Generally, for loops may begin anywhere Starting at zero simplifies using loops WFI may use any iteration variable name

13 The WFI: 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

14 The WFI: Next Iteration
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

15 The WFI: Using the Iteration Variable
The iteration variable is often used in computations in the <statement list> Scratchpad example: var fact = 1; for (var i = 0; i < 5; i = i + 1) { fact = fact * (i + 1); } fact /* 120

16 WFI: Why So Famous? Number of iterations is easy to find: it’s always n Simple to write WFI iteration variable takes on 0 through n-1 Sometimes you need 1 through n, but adding 1 is no big deal

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

18 One Way to Create an Infinite Loop
Example: for (var j = 0 ; j < 3; i = i + 1) {… } The incremented variable is not in the continuation test Easy error to make Possible after making an incomplete edit to a copy/paste or other revision

19 for Loop Practice: Flipping Coins
From Chapter 19, randNum() gives a range of integers from which a random choice is made It will return 0 (tails) or 1 (heads) To 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

20 Coin Flip: Scratchpad Example
function randNum(range) { return Math.floor(range.Math.random()); function trial (count) { var heads = 0, tails = 0; for (var i=0; i<count; i++) { if (randNum(2) == 1) heads++; else tails++; } return heads; trial (100) /* 52 */

21 1.3 Coin Flip Diagram: Nested Loops
Display a row of asterisks showing the variation from a 50 heads/50 tails trial Display the trial numbers from 1: outAns = outAns + “Trial “ + (j+1) + “: “; Notice that + has two different meanings: add and concatenate The code uses a nested loop: The <statement list> of one contains another

22 Coin Flip: Nested Loop Scratchpad Example
var headcount, outAns = "", aster; for (var j=0; j<5; j++) { headcount = trial(100); outAns = outAns +"Trial " + (j+1) + ': '; aster = ""; for (var k=0; k < Math.abs(headcount-50); k++) { aster = aster + "\n"; } outAns = outAns + aster + "\n"; outAns /* Trial 1: ** Trial 2: **** [and so on through Trial 5 – see Figure 20.3]

23 Nested Loops: Inner and Outer Loops
All programming languages allow loops to nest Inner and outer loops must use different iteration variables or else they will interfere with each other The Coin Flip Diagram uses j in the outer loop, and k in the inner loop

24 1.4 Indexing Indexing is the process of creating a sequence of names by associating a base name with a number Chapter 20; Apollo 13 Each indexed item is called an element of the sequence of items sharing the same base name In JavaScript, an index is enclosed in [square brackets]

25 1.5 Arrays In programming, a collection of elements with the same base name (that are indexed) is called an array Arrays must be declared In JavaScript, arrays are declared: var <variable> = new Array(<number of elements>) Notice that Array starts with an uppercase "A"

26 Array Variables 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 The number in parentheses gives the number of array elements To refer to an array’s length, we use <variable>.length

27 JavaScript's Array Rules
Arrays are normal variables initialized by new Array(<number of elements>) <number of elements> in the declaration is just that—the number of array elements Array indexing begins at 0 The number of elements in an array is its length Greatest index of an array is <number of elements> − 1 (because the origin is 0)

28 Array References An array reference consists of array name with an index value [enclosed in brackets] The index is also called a subscript The index value must be less than the array’s length, and can be an evaluated statement Example: var dwarf = new Array(7); dwarf[0] = "Happy"; dwarf[1] = "Sleepy"; . dwarf[10-(2*2)] = "Doc";

29 The WFI and Arrays 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

30 WFI and Arrays: Scratchpad example
for var (i = 0; i < week.length; i++) { week \[i] = dwarf[i] + dwarf[i+1%7] + "do dishes"; } week /* Happy & Sleepy do dishes, Sleepy & Dopey do dishes, . Doc & Happy do dishes */

31 Figure 20.5 The Magic Decider
Magic Decider displays (a) the initial question request, (b) the UI after tapping or clicking on the image, and (c) the image with a visible border to show its extent

32 Creating the 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

33 Magic Decider: The Array
var respond = new Array( "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy, try again", "Concentrate, and ask again", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is, no", "My sources say, no", "Outlook not so good", "Very doubtful"); function randNum( range ) { return Math.floor( range * Math.random( )); }

34 Magic Decider: Changing the DOM
<button onclick="document.getElementById('ask').innerHTML='.. . and your answer is ... '; document.getElementById('tell').innerHTML= respond[randNum(20)]"> <img src="8_ball.jpg" alt="8 Ball" width="300"/></button></p>

35 Animation Through Iteration
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 (frames per second) or 30 Hz Iteration, arrays, and indexing can be used for animation

36 Figure 20.7 The Busy Animation
The .gif images for the Busy Animation. These tiles are available at pearsonhighered.com/cs-resources

37 1.6 Animation in JavaScript
Animation in JavaScript requires three things: Using a timer to initiate animation events Prefetching the frames of the animation Redrawing a web page image

38 Animation: Using a Timer
The 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, and repeat Animation requires requires action every 30 milliseconds The activity of drawing the next frame has to be an event

39 Animation: Setting the Timer
Programmers’ timers typically “tick” once per millisecond The command to set a timer is setTimeout("<event handler>", <duration>) <event handler> is a “string” giving the JavaScript computation that runs when the timer goes off <duration> 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

40 Animation: 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

41 Animation: Referring to Timers Using a Handle
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 );

42 Animation: Starting and Stopping the Timer
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 <form> <input type="button" value="Start" onclick='setTimeout("animate()",100);'/> <input type="button" value="Stop" onclick='clearTimeout(timerID);'/> </form>

43 Animation: Prefetching
Graphics files are usually stored in a directory – ours is gifpix Display first image at first (doesn’t need to be animated yet)

44 Animation: Prefetching and Animation
To animate (overwrite image with next sequenced image): Loading images one at a time is too slow To improve speed, get all images first, store them locally, then display them Images are already numbered (to keep track of where they are in the sequence) Since they are indexed, we can use an Array var pics = new Array(12);

45 Animation: Prefetching and Initialization
Elements of the array must be initialized to an image object An image object is a blank instance of an image Initializing the 12 array elements to image objects requires an iteration and the new Image() operation: for (i=0; i<pics.length; i++) { pics[i] = new Image(); }

46 Animation: Prefetching and Using src
In the image object, there is a field called src where the image’s location is stored It's what we'll put in the <img src="..."/> tag in HTML This assignment pre-fetches the image: pics[0].src = "gifpix/Busy0.gif" The web browser saves the name, gets the file, and stores it in memory

47 Animation: Prefetching, Using src, and Visibility
There is an important difference between the prefetching and using <img src="..."/> Prefetching: Not visible on the screen <img src>: Visible on the screen There is an advantage to using both: An initial, visible image, then the animation occurs

48 Animation: Prefetching and Loops
We can use a loop to prefetch all the images: for (var i=0; i<pics.length; i++) { pics[i].src = "gifpix/Busy" + i + ".gif"; } The filename is computed using the iteration variable

49 Animation: Redrawing the 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 <img src="..."/> is encountered, the browser fills the element with its images To change the initial frame: document.images[0].src = pics[i].src;

50 Animation: Redrawing with the Event Handler
Defining the animate() event handler To animate the Busy icon we must cycle through each of the i values, one every 100ms The animate() event handler overwrites the image, sets up for the next frame, and sets the timer to call itself again: function animate() { document.images[0].src = pics[frame].src; frame = (frame + 1)%12; timerID = setTimeout("animate()", 100); }

51 Animation: Three Key Ideas
Saving state: The app needs to remember which picture to display next Prefetching: The Busy Animation prefetched images and stored them locally so they could be displayed rapidly; we can use this in other apps Changing document.images: We changed values in the browser's document.images array to animate the display

52 Figure 20.9 RPS: The Rock-Paper-Scissors App
The Rock-Paper-Scissors app's operation: (a) splash image, (b) random choice, (c) return to splash for next throw, and (d) random choice. All transitions are caused by a click/tap on the image.

53 More Animation: RPS The Rock-Paper-Scissors app is an opportunity to practice iteration, animation and click event handling Revie the RPS code in this chapter's Figure

54 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 Programmers routinely use the World-Famous Iteration (WFI), an iteration that begins at 0, tests that the iteration variable is strictly less than some limit, and increments by 1 In indexing, we create a series of names by associating a number with a base name Indexed variables are known as arrays in programming Arrays and iterations can be effectively used together, including in creating browser-based image animations


Download ppt "Fluency with Information Technology"

Similar presentations


Ads by Google