ECMM6018 Enterprise Networking For Electronic Commerce Tutorial 4 Client Side Scripting JavaScript Looping
Types of Looping While Do While For
While Statement loops through a block of code while a condition is true Syntax while (condition) { code to be executed } JavaScript is case sensitive while ≠ WHILE N.B. All JavaScript reserved keywords are case sensitive After the while statement is executed program flows to the next statement after the while is finished
While Statement ctd. The while statement can be used in 2 ways 1.) The number of repetitions is known in advance e.g. calculating the average of a class. Class Average Program var total, gradeCounter, gradeValue, average, grade; total = 0; gradeCounter =1;
While Statement ctd. while (gradeCounter <=10) { grade = window.prompt (“Enter integer grade:”, “0”); gradeValue = parseInt(grade); total = total +gradeValue; gradeCounter = gradeCounter + 1; } average = total /10; document.writeln(“ ” Class average is “ +average + “ ”);
While Statement ctd. Some Text Here
While Statement using a sentinel value 2.) Where the number of repetitions is not known in advance. In this scenario a value known as a sentinel value is used as a stopping value. Class Average Program var total, gradeCounter, gradeValue, average, grade; total = 0; gradeCounter =0;
While Statement using a sentinel value grade = window.prompt(“Enter Integer Grade, -1 to Quit:”, “0”); gradeValue = parseInt(grade); while (gradeValue != -1) { total = total + gradeValue; gradeCounter = gradeCounter +1; grade = window.prompt(“Enter Integer Grade, -1 to Quit: “, “0”); gradeValue = parseInt(grade); }
While Statement using a sentinel value if (gradeCounter !=0) { average = total/gradeCounter; document.writeln(“ Class average is “ +average + “ ”); } else { document.writeln(“ Class average is “ +average + “ ”); }
While Statement using a sentinel value Some text
Do While Statement Loops through the block at least once Syntax do { code to be executed } while (condition); example i = 0
Do While ctd. do { document.write("The number is " + i) document.write(" ") i++ } while (i <= 5);
The For Loop run statements a specified number of times Requires: - the name of a control variable - its initial value - the increment/decrement by which the loop counter is modified - the testing condition for the final value
For Loop ctd. Syntax for(initialization; test condition; increment) { code to be executed; } Example Sum the Even Integers from 2 to 100
For Loop ctd var sum = 0; for (var number =2; number<=100; number +2) { sum += number; } document.writeln(“ ”The sum of the even integers “ + “ from 2 to 100 is “ +sum + “ ”);