Loop Situation 2

Consider situation (2) next. Since the number of marks will be known when the program is executed it is once again possible to use a for loop as can be seen below:

<html>
<head>
<script type=’text/javascript’>

var Mark = 0 ;
var Sum = 0 ;
var LoopCount = 0 ;
var Average = 0.0 ;
var NumberOfStudents = 0 ;

NumberOfStudents = prompt (‘Enter the number of students:’) ;
NumberOfStudents = parseInt (NumberOfStudents) ;

for (LoopCount = 1; LoopCount <= NumberOfStudents; LoopCount++)
{ // begin for

Mark = prompt(‘Enter mark ‘ + LoopCount) ;
Mark = parseInt(Mark) ;

Sum = Sum + Mark ;

} // end for

Average = Sum / NumberOfStudents ;

alert (‘The average is ‘ + Average) ;

</script>
</head>
<body>
</body>
</html>

Notes
1. The number of times that the for loop will be executed will depend on the value which is entered for the number of students when the program is run.

2. The number of students entered is used in the calculation of the average.

Next: Loop Situation 3