Vous êtes sur la page 1sur 4

The Modulo Operator (

Odd Numbers

) and Writing out Even and

The % operator returns the remainder of a division. For example 10 2 is 5 with no


remainder so that 10%2 returns the number 0. Using long division:

On the other hand 5 3 is 1 remainder 2 or:

so that 5%3 returns 2. In this short exercise the modulo operator is used to determine
if a number is even or odd. Here is an expression that returns true if a number is
even and false if the number is odd:
number % 2 == 0

The modulo is computed first and then compared with zero. If they are equal the
number is even. Similarly,
number % 2 != 0

tests if the remainder is not zero and will be true for odd numbers. The following
short script writes out the numbers from 0 through 9 and reports if each number is
even or odd.

Exercises 1.
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<PRE>
A for loop that writes out the numbers
from 0 through 9 and labels them as
being odd or even.
<SCRIPT Language="JavaScript">
<!-for (i=0; i < 10; i++) {
if (i%2 != 0)
document.writeln(i + " is odd")
else
document.writeln(i + " is even")
}
// -->
</SCRIPT>
</PRE>
</BODY>
</HTML>

Modify this script to write out only the even numbers from 0
through 9 and then to write out only the odd/even numbers in the
the series 0 through nine. There are a few ways to do this. Try to
implement as many as possible. In particular make sure you at
least write out all the even numbers using an if statement without
an else in one loop and then use a second loop to write out all the
odd numbers using an if statement without an else.

Exercises 2.

Guessing a Number between 1 and 10

The Script below prompts the user for a number between one and ten. Modify the
script so that pressing the cancel button allows the user to quit the game. Make sure
you add an appropriate message if they give up. To do this you need to find out
what the prompt dialog returns when you press the cancel button and handle this
correctly.

<HTML>
<HEAD>
<TITLE>Pick a Number</TITLE>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
<!-guess = -1
number = Math.floor(Math.random()*10) + 1
while(number != guess){
guess = prompt("Pick a number between 1 and 10.", "")
}
//-->
</SCRIPT>
</BODY>
</HTML>

The prompt() dialog returns a string when the user presses the OK
button. The string is stored in the variable named guess. The value
in the variable named number is a number and not a string.
Fortunately, the JavaScript interpreter will see that we are testing
to see if number != guess using the not equal operator (!=). It will
therefore try to convert the string value in guess to a number
before comparing it to the value in number.