TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Modulo Operator

This C# tutorial shows how to use the modulo division operator.

Modulo 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. 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.

Intermediate Language

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

Next, this example demonstrates the mathematics behind modulo. The modulo expressions here are actually turned into constants during the C# compilation step. No rem instructions are generated.

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

The example program shows 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.

We 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.

Tip: If you perform modulo division by zero, you will get either a compile error or a runtime exception depending on the code.

DivideByZeroExceptionCompile-Time Error

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, which is called an induction variable, you can execute code at an interval based on the induction variable.

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

For

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

Often, 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.

Console.WriteLine

Discussion. 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.

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

Divide

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

Odd, Even

Performance. 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.

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.

The time required for modulo division depends on your hardware and other factors. The article "Writing Faster Managed Code: Knowing What Things Cost" is helpful. It provides a table listing times required for arithmetic operations.

Writing Faster Managed Code: MSDN

Also, you may rarely 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.

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.

Summary. We explored the modulo operator. This is implemented in the CLI as a rem instruction. We saw how the C# compiler calculates modulo divisions of constants at compile-time. Modulo division returns the remainder of the two operands.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf