COMM 1213 H1
COMP 4923 X1
JavaScript 3
(Readings: Ch. 15 Knuckles)
1
Outline
• FOR Loop
• WHILE Loop
• Verifying Input using a Loop
• Sodexo Survey revisited
2
Repetition via Loops (Ch.15)
• The FOR Loop
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!-for (i=1; i<=1000 ; i=i+1) {
document.write(i+"<BR>");
}
//--></SCRIPT>
</HEAD>
<BODY>
<P>
</BODY>
</HTML>
Sets initial loop
index value
Sets Boolean
condition on
which to stop
Sets amount to
change index on
each pass of loop
What would happen if the condition i<=1000 was changed to i<=10000000 ?
3
Using For Loops
• Processing the Pizza Toppings Form
– Figure 15.4
• Generating random lottery numbers
– Figure 15.6
4
The WHILE Loop
• Used when the number of times to loop is not known at
•
the time of writing the code.
Consider the question: Starting from 1, how many
numbers must be added until the total exceeds 25,000.
• Algorithm:
sum = 0
i=1
while sum <= 25000
sum = sum + i
i= i+1
• Program – Figure 15.8
5
Verifying
Input
Figure 15.10
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!-var pass;
pass=prompt("Enter Your Password.","");
correct=false;
while(!correct){
if((pass!="buddy")&&(pass!="pal")){
alert("You have entered an incorrect password.");
pass=prompt("Enter Your Password. Get it right this time.","");
}
else{
correct=true;
}
}
//--></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFCC">
<P><FONT SIZE="+3"><B>This page contains the darkest secrets of
the
universe.</B></FONT>
</BODY>
</HTML>
6
Other Fun with LOOPs
• Nested Loops and Tables Figure 15.12
• The Sodexo Food survey revisisted
• The Sodexo Food survey with a Loop
– Uses an array to hold the Food types
• The Sodexo Food survey with HTML
output
7
Resources
•
•
•
•
http://www.w3schools.com/js/js_examples.asp
http://www.tizag.com/javascriptT/index.php
http://www.js-examples.com/page/javascripts.html
http://javascript.internet.com/
8
THE END
[email protected]
9
© Copyright 2026 Paperzz