Loop Situation 1

Consider situation (1) first, and suppose there are 30 marks.  This would indicate that a for loop should be used, and the following program may result:

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

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

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

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

Sum = Sum + Mark ;

} // end for

Average = Sum / 30 ;

alert ('The average is ' + Average) ;

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

NOTES
1. The average is not calculated until the for loop has completed its execution at which point the total sum will have accumulated.

2. The two statements Sum = 0 ; and Sum = Sum + Mark ; highlight an important feature in programming.  When any kind of total is being accumulated, it should initially be set to zero before any loop is entered, so that it has a starting value from which it can be incremented at the appropriate point in the program.

3. By the time the loop is exited the value of LoopCount will be 31.

Next: Loop Situation 2