Loops - Monday, Week 4 What are loops? While loops Classic loop example - the for loop Parts of a loop Examples
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.
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.
While Loops Syntax: while (logical expression) { some statements } Example: while (myInt < 10) { ask for another integer; }
While Loop Structure Group of Statements A while ( logical expression ) {.. Group of Statements B. } Group of Statements C
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.
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+” ”); }
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+” ”); }
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 + “ ”); }
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">'); }
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++?
MiniLab #5 Now we can show our entire array of records using a loop! Then we will put the data into a table format.