Modulo of Negative Numbers in C

In this tutorial, we will look at a few examples of modulus on negative numbers in C.

What is Modulus of Negative number?

Users can find the modulus of a negative number by leaving off the minus (-) sign. To get the modulus of a number, add vertical lines all around it. Remember that a negative number's modulus is created by multiplying it by one, as in the case of the formula (-9) = 9.

"Modulus":

The modulo, sometimes known as "mod", stands for the residue of a division. In 1801, Gauss published a dissertation on modular arithmetic. A mathematical definition afterwards offered by Donald Knuth is now accepted by everyone.

The modulo operator returns the outcome of a division. But things get a little trickier when negative numbers are included. Let's examine a few example of the modulus of negative numbers. Observe the programs' output as well.

Example:

C program:

Output:

C Program Output: -7 % 11 = -7

C++ program:

Output:

C++ Program Output: -7 % 11 = -7

Example:2

In some circumstances, regardless of the dividend's sign, you might need to make sure that the modulo operation's outcome is positive. Adding the divisor to the result until it becomes non-negative is one approach to accomplish this. This method of getting a positive remainder for a negative dividend is widely used in C.

C program:

Output:

C Program Output: 4 % -9 = 4

For Reference:

C++ program:

Output:

C Program Output: 4 % -9 = 4

Example:3

C program:

Output:

C Program Output: -4 % 9 = -4

For Reference:

C++ program:

Output:

C++ Program Output: -4 % 9 = -4

Chart:

NumeratorDenominator
XYX / YX % Y
++++
+--+
-+--
--+-

Conclusion:

When used with negative values, the modulo operation in C preserves the dividend's sign. Although this behaviour initially appears illogical, it follows to a reliable rule. You can add the divisor to the result until it stops being negative in order to guarantee that the result of the modulo operation is positive for negative dividends.

When working on a variety of programming jobs, such as circular buffers, date computations, and handling negative offsets, it is imperative to comprehend the modulo operation's behaviour with negative values. It enables you to create trustworthy and precise code, avoiding unforeseen mistakes and guaranteeing the accuracy of your algorithms.