Sunday, October 16, 2011

RAPTOR SKILL - Modulus Operator - Part 1

Every programming language has a modulus operator. Curiously RAPTOR has two, mod and rem. They can be used interchangeably. But what does modulus do and why do we need it? It's used to find the remainder after a division. For example,
20 divided by 6 goes 3 times with 2 remainder. So the RAPTOR expression 20 mod 6 would compute to 2. For another example,
26 divided by 7 goes 3 times with 5 remainder. So 26 mod 7 = 5.

More Examples:
  • 17 divides by 5 to yield 3 with remainder 2. So, 17 mod 5 (or 17 rem 5) = 2.
  • 27 mod 10 = 7, because 10 divides into 27 twice with 7 as remainder.
  • Dividing 21 by 4 gives the result 5 with remainder 1. So, 21 mod 4 = 1.
  • 28 mod 5 = 3 (28 divided by 5 = 5 with 3 remainder).
  • 27 mod 9 = 0 (27 divides evenly by 9)
You can easily test the output of a modulus expression in RAPTOR by entering the expression in an Output symbol. Can you determine what will be output by the following RAPTOR expression?
    If you said 5, you are correct because 12 divided by 7 goes once with 5 remainder. It might surprise you to learn that the modulus operator has many important uses in computer programming. That last example illustrates one use, detecting exact multiples of any integer. If a number mod 9 = 0, then the number is a multiple of 9. If a number mod 7 = 0, the number is a multiple of 7.

    Another use is determining if a number is even or odd. If any number mod 2 = 0, then the number is even. If number mod 2 = 1, the number is an odd number.

    mod operator used to detect odd/even in selection
    Did you notice that we began every expression using mod with if?
    That's because the mod operator is usually used in a selection in a computer program.

    A very practical application of the modulus operator is making change. See Modulus Operator - Part 2 for more about this. Vending machines are coded to use the modulus operator to return your correct change.