Negative numbers and the modulo operator in C

This is an example C program illustrating the behaviour of C's modulo/remainder operator (%) for negative numbers. The modulo operator is not mathematically correct, since it turns negative numbers into negative numbers. The macro MOD(a,b) gives the correct modulo operation.

#include <stdio.h>

#define MOD(a,b) ((((a)%(b))+(b))%(b))
#define MODULO(a,b) printf ("%s %% %s = %d\tMOD (%s,%s) = %d\n",\
			    #a, #b, a % b, #a, #b, MOD (a,b))

int main ()
{
    MODULO (10, 4);
    MODULO (-10, 4);
    MODULO (9, 4);
    MODULO (-9, 4);
    MODULO (-7, 4);
    return 0;
}

(download)

The output of the example looks like this:

10 % 4 = 2	MOD (10,4) = 2
-10 % 4 = -2	MOD (-10,4) = 2
9 % 4 = 1	MOD (9,4) = 1
-9 % 4 = -1	MOD (-9,4) = 3
-7 % 4 = -3	MOD (-7,4) = 1


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer