**Then:** Rem performs the computation that returns the remainder of the division. It pushes that value onto the evaluation stack.

**Here:** This example demonstrates the math behind modulo. The expressions here are turned into constants during the C# compilation step.

**Important:** We see that 1000 and 100 divide into parts of 90 with a remainder of 10.

**Note:** If the first argument to the predefined modulo operator is 81 and the second operand is 80, the expression evaluates to a value of 1.

**Note:** This example shows how to write to the screen every ten iterations in the for-loop.

**Important:** The 3 numbers in the condition in the if-statement can have any values, but we cannot divide by 0.

**Note:** We do not often need to compute numeric remainders for user consumption. The regular division operator may be more useful here.

**Odd:** You can use modulo to test for odd numbers and even numbers. You can define odd numbers as not-even numbers.

**But:** The total time required for individual modulo operations is tiny compared to other tasks such as disk reads or network accesses.

**So:** If you can reduce those operations with modulo division, you can improve overall performance.

**Tip:** You can apply a technique called "strength reduction" manually to convert the modulo operation into a subtraction or addition.

**And:** To do this, add another field or local variable. Then, in each iteration of the loop, decrement it and test it against zero.

**Then:** When zero is reached, set it to its maximum value again. This resets the pattern.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.

Home

Dot Net Perls