Data Validation

Although the entrance controlled while loop is the loop to choose in most circumstances, the exit controlled do while loop is extremely useful when validating data.  For example, if we wished to ensure that only marks in the range 1 to 100 were entered we could do it as follows:

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

var Mark = 0 ;

do
{ // begin do while

Mark = prompt (‘Enter a mark in the range 0 – 100’) ;
Mark = parseInt(Mark) ;

if (Mark < 1 || Mark > 100)
{ // begin if

alert ("Invalid mark, please re-enter") ;

} // end if

} // end do while
while (Mark < 1 || Mark > 100) ;

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

Next: Choosing a Loop Structure Review