Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Modulus of Negative Numbers in C
In C programming, the modulus operator (%) can be used with negative numbers, but the result depends on the sign of the dividend (left operand). The sign of the result always matches the sign of the dividend, regardless of the divisor's sign.
Syntax
result = dividend % divisor;
Rule for Sign Determination
The sign of the modulus result follows this rule −
- If dividend is positive, result is positive
- If dividend is negative, result is negative
- The divisor's sign does not affect the result's sign
Example 1: Positive Dividend, Negative Divisor
#include <stdio.h>
int main() {
int a = 7, b = -10;
printf("Result of %d %% %d = %d<br>", a, b, a % b);
return 0;
}
Result of 7 % -10 = 7
Example 2: Negative Dividend, Positive Divisor
#include <stdio.h>
int main() {
int a = -7, b = 10;
printf("Result of %d %% %d = %d<br>", a, b, a % b);
return 0;
}
Result of -7 % 10 = -7
Example 3: Both Operands Negative
#include <stdio.h>
int main() {
int a = -7, b = -10;
printf("Result of %d %% %d = %d<br>", a, b, a % b);
return 0;
}
Result of -7 % -10 = -7
Example 4: Modulus with Division (Operator Precedence)
When modulus and division operators appear together, they have the same precedence and are evaluated left to right −
#include <stdio.h>
int main() {
int a = 7, b = -10, c = 2;
printf("Result of %d %% %d / %d = %d<br>", a, b, c, a % b / c);
printf("Step by step: (%d %% %d) / %d = %d / %d = %d<br>",
a, b, c, a % b, c, (a % b) / c);
return 0;
}
Result of 7 % -10 / 2 = 3 Step by step: (7 % -10) / 2 = 7 / 2 = 3
Advertisements
