C# Modulo Operator

Percentage symbol

Modulo division computes a remainder. The modulo operator provides a way to execute code once every several iterations of a loop. It uses the percentage sign character in the lexical syntax. It has some unique properties.

Estimated costs of instructions

Add:         1 ns
Subtract:    1 ns
Multiply:  2.7 ns
Divide:   35.9 ns

Example

Note

Modulo division is expressed with the percentage sign % character. It is implemented with the rem instruction in the intermediate language. The rem instruction takes the top two values on the evaluation stack and performs the mathematical computation that returns the remainder of the division, and then pushes that value onto the evaluation stack for the next instructions to use.

This example demonstrates the mathematics behind modulo and the modulo expressions here are actually turned into constants during the C# compilation step, so no rem instructions are generated.

Program that uses modulo operator [C#]

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
The C# programming language

Description. The purpose of the example program is to show the remainders of the divisions of the two integers at each step. The runtime never performs modulo divisions here as the C# compiler actually does the divisions.

Results. You can see that 1000 and 100 divide into parts of 90 with a remainder of 10. 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. Finally, if you apply modulo division on the same two operands, you receive 0 because there is no remainder. If you perform modulo division by zero, you will get either a compile error or a runtime exception depending on how well the C# compiler can analyze your code.

Modulo loop example

You can actually apply the modulo operator in the C# language in a loop to achieve an interval or step effect. If you use a modulo operation on the loop index variable, which is called an induction variable, you can execute code at an interval based on the induction variable. This example shows how you can write to the screen every ten iterations in the for-loop.

Program that uses modulo division in loop [C#]

using System;

class Program
{
    static void Main()
    {
	//
	// Prints every tenth number from 0 to 200.
	// Includes the very 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
If keyword

Description. Often you will find that modulo divisions are performed in if-statements and used in control flow. The three numbers in the condition in the if-statement can be any value with the exclusion of a division by zero, which the compiler will reject. However, to keep your code simple often you can test against zero.

Console.WriteLine Intermediate Language

Real program uses

The modulo division operation has several common uses in programs. You can use modulo division in loops to only execute code every several iterations, such as shown above. This can reduce complexity and improve performance in real code. You do not often need to compute numeric remainders for user consumption however. The regular division operator may be more useful to you.

Divide Numbers

Performance

Performance optimization

The modulo division operator in the C# language is considerably slower than other arithmetic operators such as increment and decrement or even multiply. This is basically a hardware limitation on computers.

However, the total time required for individual modulo operations in the C# language 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 greatly improve overall performance.

Nanoseconds. The time required in nanoseconds for modulo division will depend on your exact hardware and probably other factors such as the evaluation stack and function structure in your code. The article "Writing Faster Managed Code: Knowing What Things Cost" by Jan Gray of Microsoft Corporation provides a table listing times required for arithmetic operations.

MSDN referenceProgramming tip

Strength reduction as optimization. Rarely you may have a modulo division in a hot path in your program and this can sometimes cause a measurable loss of performance. This will almost always occur in a loop body or in a recursive method.

In this case, you can apply a compiler optimization technique called "strength reduction" manually to convert the modulo operation into a subtraction or addition. To do this, add another field or local variable and in each iteration of the loop, decrement it and test it against zero. When zero is reached, set it to its maximum value again.

Summary

.NET Framework information

We explored the modulo operator—which is implemented in the Common Language Runtime as a rem instruction. We saw how the C# compiler calculates modulo divisions of constants at compile-time; how modulo division returns the remainder of the two operands; how to use modulo division in loops to achieve an interval effect; how real-world programs use modulo divisions; and how to optimize modulo.

Odd and Even Numbers Number Examples
.NET