The modulus operator is the only arithmetic operator used in programming that
was not taught in first grade, at least not to me.
It returns the remainder of a division operation.
For example, 10 / 3 equals 9, with 1 left over. Long division is cool,
so 10 % 3 equals 1. The correct way to read that is "ten modulo three".
I saw it in a C++ book, so it must be true.
{
int $mod = 10 % 3;
print ($mod + "\n");
}
The modulus operator can do some very cool things. For example:
Number wrapping, think screen wrapping in Asteroids.
Suppose you want to constrain an input number to a number between 0 and 10.
if the number reaches 10, go back to zero and start over.
This example uses a loop.
{
int $i;
int $mod;
for ($i = 0; $i < 100; $i++)
{
$mod = $i % 10;
print ($i + " Screen wrap : " + $mod + "\n");
}
}
You can also use it to find out if a number is odd, or even by moduloing (not sure of the correct terminology there) by 2.
This example uses a loop and conditional statements.
{
int $i;
for ($i = 0; $i < 100; $i++)
{
print ($i + " is ");
if ($i % 2 == 0 )
print "even.\n";
else
print "odd.\n";
}
}
Keep the modulus in mind, because one of the first scripting exercises uses it quite a bit.
|