Download presentation
Presentation is loading. Please wait.
1
Loops - Monday, Week 4 What are loops? While loops Classic loop example - the for loop Parts of a loop Examples
2
What are loops? Loops are the way we can do something multiple times Sometimes it’s the same thing repeated, other times we want to change something slightly each repetition. A loop will repeat a set of statements over and over until a stop condition is met.
3
While Loops A while loop repeats a set of statements while a logical expression is true. For example, we could repeat asking for a big number as long the number given was less than 10.
4
While Loops Syntax: while (logical expression) { some statements } Example: while (myInt < 10) { ask for another integer; }
5
While Loop Structure Group of Statements A while ( logical expression ) {.. Group of Statements B. } Group of Statements C
6
Parts of a Loop Initialize some variables Loop while some condition is true. Change some part of the loop conditions so the loop will stop.
7
Parts of a Loop In general a for loop makes the parts of a loop explicit. for (init; test; step) { statements; } for (i=0; i<11; i++) { document.writeln(“i = “+i+” ”); }
8
Classic Loop Example Frequently we want to do something to all items in an array. This requires being able to generate the numbers from 0 to n. A for loop is an easy way to do this. Print out the numbers from 0 to 10: for (i=0; i<11; i++) { document.writeln(“i = “+i+” ”); }
9
Classic Loop Example Looping through the elements of an array can be done easily with a for loop. for (var i=0; i < StudentArray.length; i++) { document.writeln (“Name: “ + StudentArray[i].name + “ phone: “ + StudentArray[i].phone + “ ”); }
10
Examples Placing images on your web page var i; for ( i = 0; i < colors.length; i++ ) { // write document.write('<IMG SRC="'); document.writeln(colors[i]+'ball.gif">'); }
11
Examples The following for loop and while loops are equivalent: for (i=0; i<11; i++) { document.writeln(“i = “+i+” ”); } i=0; while (i < 11) { document.writeln(“i = “+i+” ”); i++; } What happens in the while loop if you forget the i++?
12
MiniLab #5 Now we can show our entire array of records using a loop! Then we will put the data into a table format.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.