This C# operator gets a remainder. It provides a way to execute code once every several iterations of a loop. To use modulo, we specify "%"—the percentage sign character.
As with all low-level operations, modulo has a specific cost. The cost of these operations is relevant for some high-performance C# programs.
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.
using System; // When 5 is divided by 3, the remainder is 2. Console.WriteLine(5 % 3); // 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);2 10 10 1 0
We can use modulo in a loop for an interval or step effect. If we use a modulo operation on the loop index variable, we can execute code at an interval.
for
-loop. We use an if
-statement with modulo.if
-statement can have any values, but we cannot divide by 0.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); } } } }0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190
If you use modulo by 0, you will get a compile error or a runtime exception. The denominator must never be zero.
class Program { static void Main() { int zero = int.Parse("0"); int result = 100 % zero; } }Unhandled exception. System.DivideByZeroException: Attempted to divide by zero. at Program.Main()...
Modulo is slower than other arithmetic operators such as increment and decrement or even multiply. This is a hardware limitation on computers.
Add: 1 ns Subtract: 1 ns Multiply: 2.7 ns Divide: 35.9 ns
Modulo has many common uses in programs. You can use modulo division in loops to only execute code every several iterations. This can improve real code.
List
. We can use modulo for this.Technically the "%" operator in C# is a remainder operator. In testing, this is the same as modulo except when we are using a negative number as the divisor.
Modulo division returns the remainder of the 2 operands. We use the "percent" symbol for modulo in the C# language—this is a powerful operator, but it has its nuances.