Example 2

The code shown here is a small program that works out whether the integer number entered is odd or even. Comments have been added to the code.

<html>
<head>

<script>

// Declare and initialise variables
var Number = 0;

// Get Number
Number = prompt ('Type in an integer number (0 to 999): ') ;
Number = parseInt (Number) ;

// Validate data entry to allow only integers in the range 0 to 999 to be entered
while (Number < 0 || Number > 999)
{  // begin while
Number = prompt ('You must enter a number between 0 and 999. Try again') ;
} // end while

// The % operator is used for integer division and will give the remainder.
// Ex. 1: 7 % 2 = 3 remainder 1 - The 3 will be discarded and the 1 retained as the answer.
// Ex. 2: 4 % 2 = 2 remainder 0 - The 2 will be discaredd and the 0 retained as the answer.
// The use of integer division here is to determine if Number is even or odd.
// If the remainder is 0 the number is even if it is 1 the number is odd
if (Number % 2 == 0)
{ // begin if
alert (Number + ' is an even number.') ;
} // end if
else
{ // begin else
alert (Number + ' is an odd number.') ;
} // end else

</script>
</head>
<body>

</body>
</html>

Next: Example 3