Chapter 7: Looping in JavaScript

กก

If we need to perform repetitive procedure or processes in JavaScript, we could achieve it by using the While statement.  The while statement allows us to control the number of times a procedure is performed. It is important to make that the repetition is not endless. I will illustrate the algorithm using the example bellow. The program will produce a pop-up dialog box 8 times prompting the user to enter the marks 8 times, then it will add up the marks and show the average mark.:

Example: 

กก

<html>

<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Sample JavaScript using While</title>
<script language=javascript>

var sum,
mark1,
mark2,
counter,
avg;

sum=0;
counter=1;

while(counter<=8) {

mark1=window.prompt("Enter your mark","0");
mark2=parseInt(mark1);
sum=sum+mark2;
counter=counter+1;
}
avg=sum/8;
document.writeln("<H2> Average mark is "+avg+"</H2>");




</script>
</head>

<body>

<h2 align="center"><font face="Arial">Sample JavaScript using While</font></h2>

</body>

</html>
กก

Click on the testing page

กก

<Previous Chapter> [Back to Main Page]