Modulus on Negative Numbers
What will be the output of the following C program?
c
#include <stdio.h>int main(){ int a = 3, b = -8, c = 2; printf("%d", a % b / c); return 0;} |
C++
#include <iostream>using namespace std;int main() { int a = 3, b = -8, c = 2; cout << a % b / c; return 0;} |
1
% and / have same precedence and left to right associativity. So % is performed first which results in 3 and / is performed next resulting in 1. The emphasis is, sign of left operand is appended to result in case of modulus operator in C.
c
#include <stdio.h>int main(){ // a positive and b negative. int a = 3, b = -8; printf("%d", a % b); return 0;} |
C++
#include <iostream>using namespace std;int main() { int a = 3, b = -8; cout << a % b; return 0;} |
Output
3
c
#include <stdio.h>int main(){ // a negative and b positive int a = -3, b = 8; printf("%d", a % b); return 0;} |
C++
#include <iostream>using namespace std;int main(){ // a negative and b positive int a = -3, b = 8; cout << a%b; return 0;} |
Output
-3
But from the definition of remainder (as stated here https://en.wikipedia.org/wiki/Remainder) it should always be a least positive integer that should be subtracted from a to make it divisible by b (mathematically if, a = qb + r then 0 ≤ r < |b|).
So, in the above example -3 is not our real remainder because it is negative.
Therefore, in C/C++ language we always find remainder as (a%b + b)%b (add quotient to remainder and again take remainder) in order to avoid negative remainder.
c
#include <stdio.h>int main(){ // a and b both negative int a = -3, b = -8; printf("%d", a % b); return 0;} |
C++
#include <iostream>using namespace std;int main() { // a and b both negative int a = -3, b = -8; cout << a % b; return 0;} |
Output
-3
Anyone can predict the output of a modulus operator when the both operands are positive. But when it comes to the negative numbers, different languages give different outputs.
In C language, modulus is calculated as,
a % n = a – ( n * trunc( a/n ) ).
For example,
8 % -3 = 8 – ( -3 * trunc(8/-3) )
= 8 – ( -3 * trunc(-2.666..) )
= 8 – ( -3 * -2 ) { rounded towards zero }
= 8 – 6
= 2
For more info, please see https://en.wikipedia.org/wiki/Modulo_operation
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



