Going Mad for Mod

I have two questions when it comes to using the % operator: Is it modulus or modulo? And which value comes first?

The modulus is a number being manipulated.

Modulo is the operation, and the name of the % operator in C.

If you want to confuse people, use both terms. A while back, I decided to use modulo only, but here’s a specific example to explain the difference and potentially confuse you further:

10 % 3 = 1

Read this statement as “ten modulo three equals one.” The number three is the modulus. Got it?

Good! Now, never bring it up again.

The next question I have is regarding the order of operations. The modulo (see?) returns the remainder of one value divided by another. (The second value is the modulus, which I’m bringing up again because I find it difficult to stick to my own rules.) So 10 % 3 = 1 because one is the remainder of ten divided by three. But 3 % 10 is three. In fact:

A % B = A

This expression holds true for all values of B greater than A. When A and B are equal, the result is zero. Otherwise, the result is the modulo of B against A when A is the larger value.

Here is some code where the output may help you further understand the modulo operator and confirm that the largest value always comes first:

2022_08_06-Lesson.c

#include <stdio.h>

int main()
{
    int x,y;

    for( x=1,y=10; y>0; x++,y-- )
        printf("%2d %% %2d = %d\n",x,y,x%y);

    printf("%d %% %d = %d\n",5,10,5%10);
    printf("%d %% %d = %d\n",2,8,2%8);
    printf("%d %% %d = %d\n",7,1500,7%1500);
    printf("%d %% %d = %d\n",4,4,4%4);
    printf("%d %% %d = %d\n",10,5,10%5);
    printf("%d %% %d = %d\n",8,2,8%2);
    printf("%d %% %d = %d\n",1500,7,1500%7);
    return(0);

}

The for loop generates expressions with values cycling between one and 10. The other statements output specific values. Everything output appears as an expression:

 1 % 10 = 1
 2 %  9 = 2
 3 %  8 = 3
 4 %  7 = 4
 5 %  6 = 5
 6 %  5 = 1
 7 %  4 = 3
 8 %  3 = 2
 9 %  2 = 1
10 %  1 = 0
5 % 10 = 5
2 % 8 = 2
7 % 1500 = 7
4 % 4 = 0
10 % 5 = 0
8 % 2 = 0
1500 % 7 = 2

The first five lines of output confirm that A % B = A. When the values get larger, starting with 6 % 5, you see the true modulo. Ditto for the other lines, when the second value is larger. Also for 4 % 4, the result is zero in that four evenly divides into itself.

Despite all the text I’ve inscribed into this post, I may still forget that the larger value comes first when crafting a modulo expression. But perhaps by writing some 368 words on the topic, it may finally stick in my brain.

Leave a Reply