Loop Situation 3 Option 1

Now we consider which type of loop should be used.  Obviously, a for loop is not appropriate in this situation.  We could try a do while loop as follows:

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

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

do
{ // begin do while

Mark = prompt(‘Enter mark (Type a mark of 0 to exit): ‘) ;
Mark = parseInt(Mark) ;

Sum = Sum + Mark ;

NumberOfStudents = NumberOfStudents + 1 ;

} // end do while
while (Mark != -1)

Average = (Sum + 1) / (NumberOfStudents - 1) ;

alert (‘The average is ‘ + Average) ;

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

Notes

  1. A running total is introduced to keep track of the number of marks entered in order that the average may be calculated.
  2. When the SENTINEL of -1 is entered it is added to the Sum, which will reduce the Sum by -1. This will affect the final answer so in the calculation of the average + 1 must be added to Sum. There is a similar issue with NumberOfStudents because it is incremented by 1 for this final SENTINEL mark.  Therefore, The NumberOfStudents at the end will be 1 greater than the number of actual students and because of this the calculation must be adjusted to take this into account. These adjustments make the calculation more complicated than it should really be. It is for this reason that the do while loop in this instance should be avoided in situations like this because it can lead to bad programming practice.

Next: Loop Situation 3 Option 2