C# modulus operator
Categories:
Understanding the C# Modulus Operator (%)

Explore the C# modulus operator (%), its behavior with positive and negative numbers, and common use cases for remainder calculations.
The modulus operator, represented by the percentage sign (%
) in C#, is a fundamental arithmetic operator that computes the remainder of a division operation. While often confused with simple division, its purpose is distinct: it tells you what's left over after one number is divided by another a whole number of times. Understanding its behavior, especially with negative operands, is crucial for writing robust and predictable code.
Basic Modulus Operation
At its core, the modulus operator returns the remainder of the division of two numbers. For positive integers, its behavior is straightforward and aligns with what you might expect from elementary arithmetic. The result will always have the same sign as the dividend (the first operand).
int result1 = 10 % 3; // result1 is 1 (10 = 3 * 3 + 1)
int result2 = 15 % 4; // result2 is 3 (15 = 3 * 4 + 3)
int result3 = 7 % 7; // result3 is 0 (7 = 1 * 7 + 0)
int result4 = 7 % 10; // result4 is 7 (7 = 0 * 10 + 7)
Console.WriteLine($"10 % 3 = {result1}");
Console.WriteLine($"15 % 4 = {result2}");
Console.WriteLine($"7 % 7 = {result3}");
Console.WriteLine($"7 % 10 = {result4}");
Basic modulus operations with positive integers
Modulus with Negative Numbers
The behavior of the modulus operator becomes more nuanced when one or both operands are negative. In C#, the sign of the result of a modulus operation is always the same as the sign of the dividend (the first operand). This is a key distinction from some other programming languages or mathematical definitions where the result might always be positive or have the sign of the divisor.
int resultNeg1 = -10 % 3; // resultNeg1 is -1 (-10 = -4 * 3 + 2, but C# uses -3 * 3 + (-1))
int resultNeg2 = 10 % -3; // resultNeg2 is 1 (10 = -3 * -3 + 1)
int resultNeg3 = -10 % -3; // resultNeg3 is -1 (-10 = 3 * -3 + (-1))
Console.WriteLine($"-10 % 3 = {resultNeg1}");
Console.WriteLine($"10 % -3 = {resultNeg2}");
Console.WriteLine($"-10 % -3 = {resultNeg3}");
Modulus operations involving negative numbers
flowchart TD A[Start Modulus Calculation] --> B{Is Dividend Negative?} B -- Yes --> C[Result Sign is Negative] B -- No --> D[Result Sign is Positive] C --> E[Calculate Remainder Magnitude] D --> E E --> F[Combine Sign and Magnitude] F --> G[End: Return Remainder]
Decision flow for determining the sign of the modulus result in C#
(a % n + n) % n
for positive n
.Common Use Cases
The modulus operator is incredibly versatile and finds application in various programming scenarios, from simple checks to complex algorithms.
1. Checking for Even or Odd Numbers
A number is even if number % 2
is 0, and odd if number % 2
is 1 (or -1 for negative odd numbers).
2. Cycling Through Arrays or Lists
Use index % array.Length
to wrap around an array, ensuring the index always stays within bounds.
3. Time Calculations
Convert total seconds into minutes and remaining seconds (e.g., totalSeconds % 60
).
4. Hashing Functions
Often used to map a large range of values to a smaller, fixed range (e.g., hashCode % tableSize
).
5. Digital Clock Display
To display hours in a 12-hour format, you might use (hour - 1) % 12 + 1
.
// Check for even/odd
int num = 17;
if (num % 2 == 0)
{
Console.WriteLine($"{num} is even.");
}
else
{
Console.WriteLine($"{num} is odd.");
}
// Cycling through an array
string[] days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
int currentDayIndex = 5;
int nextDayIndex = (currentDayIndex + 1) % days.Length;
Console.WriteLine($"Next day after {days[currentDayIndex]} is {days[nextDayIndex]}");
// Time calculation
int totalSeconds = 150;
int minutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;
Console.WriteLine($"{totalSeconds} seconds is {minutes} minutes and {remainingSeconds} seconds.");
Practical examples of the modulus operator in C#
x % 0
will result in a DivideByZeroException
at runtime, just like division by zero.