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

- A running total is introduced to keep track of the number of marks entered in order that the average may be calculated.
- 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.