Use the modulo division operator to get remainders from dividing numbers.
Modulo. This operator gets a remainder. It provides a way to execute code once every several iterations of a loop. It uses the percentage sign character in the lexical syntax.
Modulo, notes. Modulo has some unique properties. As with all low-level operations, it has a specific cost. We analyze modulo division in the C# language.DivideOdd, EvenEvery Nth Element
An example. Modulo division is expressed with the percentage sign. It is implemented with "rem" in the intermediate language. Rem takes the top 2 values on the evaluation stack.
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
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);
Example 2. You can apply modulo in a loop to achieve an interval or step effect. If you use a modulo operation on the loop index variable, you can execute code at an interval.
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
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)
Performance, table. The time required for modulo division depends on hardware and other factors. Some analysis from Microsoft is helpful. This page provides a table listing times required.Writing Faster Managed Code: Microsoft Docs