C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
C# program that uses modulo operator
using System;
class Program
{
static void Main()
{
// When 1000 is divided by 90, the remainder is 10.
Console.WriteLine(1000 % 90);
// When 100 is divided by 90, the remainder is also 10.
Console.WriteLine(100 % 90);
// When 81 is divided by 80, the remainder is 1.
Console.WriteLine(81 % 80);
// When 1 is divided by 1, the remainder is zero.
Console.WriteLine(1 % 1);
}
}
Output
10
10
1
0
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.
C# program that uses modulo division in loop
using System;
class Program
{
static void Main()
{
//
// Prints every tenth number from 0 to 200.
// Includes the first iteration.
//
for (int i = 0; i < 200; i++)
{
if ((i % 10) == 0)
{
Console.WriteLine(i);
}
}
}
}
Output
0
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
Estimated costs of instructions:
Add: 1 ns
Subtract: 1 ns
Multiply: 2.7 ns
Divide: 35.9 ns
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.