Loop Situation 3 Option 2

The only alternative left to the programmer is to use a while loop, which may be as follows:

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

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

Mark = prompt('Enter mark (Type a mark of -1 to exit): ') ;
Mark = parseInt(Mark) ;

while (Mark != -1)
{ // begin while

Sum = Sum + Mark ;

NumberOfStudents = NumberOfStudents + 1 ;

Mark = prompt('Enter mark (Type a mark of -1 to exit): ') ;
Mark = parseInt(Mark) ;

} // end while

Average = Sum / NumberOfStudents ;

alert ('The average is ' + Average) ;

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

Notes

  1. This program highlights an important feature of while loops.  When a sequence of data is being entered in succession, the first value is read in before the start of the loop.  This is necessary in order that we have something to test in the condition at the start of the loop.  Each succeeding data value is read in within the loop once the previous value has been processed.  This will normally be at the end of the loop.  If a programmer omits the data input inside the loop there is a very high risk that the programs execution will get stuck permanently within the loop since no new values will be read in and tested for the exit condition.
  2. In general, if the number of iterations of a loop as not known in advance, the while loop is more appropriate than the do while loop in most cases.

Next: Data Validation