JavaScript VIIterationExamplesJavaScript constructswhileComparison of if and whileExampleWhile Loop ExampleWhile Loop PageCounter-Driven LoopsCounter + while loopSlide 12Counter-Driven Loops PageCommon ErrorsMore Common ErrorsAn Alternate FormulationSlide 17Countdown PageLoops Without CountersOther ExamplesFor loopsFor syntaxSpecial caseSlide 24JavaScript VILoops & Repetition StatementsIterationInstructions on a shampoo bottleput on hairlatherrinserepeatWe call this "iteration"executing some action repeatedlyusually not forever, but according to some algorithmExamplesRoll the dice until you make your roll doublesCalculate a grade for each student in the classScan each word in a document, looking for one that is misspelledCompute the monthly interest on the loan for each of the next 12 monthsJavaScript constructswhile loopUsed to repeatedly perform a sequence of statements as long as some condition holdsfor loopUsed to repeatedly perform a sequence of statements for a specified number of timeswhileSyntax… while (condition) {... body ...}…Meaning:Upon reaching the while, check the condition.Execute the body of the loop repeatedly as long as the condition remains true.If and when the condition becomes false, then exit the loop and continue with the rest of the programNote that the body of the loop must change the condition. Why?Comparison of if and whileAppearance is similarif (condition) {... body ...}while (condition) {... body ...}Meaning is similartrue condition means body is executedDifference is in repetitionbody in if statement is executed at most oncebody in while loop is repeatedly executed until condition is falseExampleGet a positive number N as value from user, compute and print the sum from 1 to NN = prompt(“Enter a number:”, “0”);N = parseInt(N);sum = 0;i = 1;while (i <= N) {sum = sum + ii = i + 1;}document.write(“Sum of numbers from 1 to “ + N + “ is: “ + sum + “.”);Exercise: modify this to compute the sum of all numbers between two user-specified number M and N, with M < N.What if we forgot this step?8While Loop Exampleexample: roll two dice repeatedly until doubles are obtainedsample output:note: even though while loops and if statements look similar, they are very different control statementsan if statement may execute its code 1 time or not at alla while loop may execute its code an arbitrary number of times (including not at all)9While Loop PageCounter-Driven LoopsThe Sum of 1 to N program was an example of a “counter-driven” loopOften we want to repeat an action some number of timesroll the dice 1000 timesprint out the first 10 lines of a filewe need a loop that executes some number of timesCounter + while loopGeneral form to execute body N timesvar counter = 0;while (count < N){bodycounter = counter + 1;}Notecounter is only used to keep track of the repetitionswhat happens if we don't increment the counter?why isn't the test count <= N or count == N?12Counter-Driven Loopsexamples:13Counter-Driven Loops PageCommon ErrorsBody of the code doesn't change the conditioni = 1;while (i <= N) { sum = sum + i}i = 0;while (i <= N) { sum = sum + i i = i + 1;}Wrong initializationi = 1;while (i <= N) { i = i + 1; sum = sum + i}Modification step is out of orderMore Common ErrorsWrong conditioni = 1;while (i < N) { sum = sum + i}// print odd numbers < 10x = 1;while (x != 10) { document.writeln(x); x = x + 2;}How about this?An Alternate FormulationCount down instead of upvar counter = N;while (count > 0){bodycounter = counter - 1;}Pointsis this the right test?Examplecount.htmlPurpose: Count down to 0Some new features:Continuous addition of text to text area document.CountForm.Output.value = document.CountForm.Output.value + count + "\n";document.CountForm.Output.value = document.CountForm.Output.value + count + "\n";Countdown PageLoops Without CountersLoop conditions can be based on any Boolean expressionNot just involving countersSuch as comparison of two variables or quantitiesExample: roll.htmlPurpose: keep rolling until doublesAgain using continuous addition of text to text area document.DiceForm.Output.value = document.DiceForm.Output.value + "You rolled: " + roll1 + " " + roll2 + "\n";document.DiceForm.Output.value = document.DiceForm.Output.value + "You rolled: " + roll1 + " " + roll2 + "\n";Other Examplesstats.htmlFor loopsSimplifies the counter-driven patternTo execute body N timesvar counter = 0;while (count < N){bodycounter = counter + 1;}For-loop versionfor (counter = 0; counter < N; counter = counter + 1){body}For syntaxfor (variable = initial value; exit condition; increment step)fairly flexiblebut almost always used for simple countingfor (i = 0; i < N; i++){body}Noterepeats the body N timesi is a conventional name for a loop counteri++ is the same as i = i + 1Special casethe for loop is a special case of the while loopyou can always rewrite a for loop as a while loopfor (variable = initial value; condition; increment step){body}Rewritten asvariable = initial value;while (condition){bodyincrement step;}Example“For” version of Sum-1-to-N programN = prompt(“Enter a number:”, “0”);N = parseInt(N);sum = 0;for (i = 1; i <= N; i++) {sum = sum + i;}document.write(“Sum of numbers from 1 to “ + N + “ is: “ + sum +
View Full Document