Solution for Exercise 11-7

ex1107

#include <stdio.h>

int main()
{
    const int value = 5;
    int a;

    printf("Modulus %d:\n",value);
    for(a=0;a<30;a++)
        printf("%d %% %d = %d\n",a,value,a%value);
    return(0);
}

Output

Modulus 5:
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2
8 % 5 = 3
9 % 5 = 4
10 % 5 = 0
11 % 5 = 1
12 % 5 = 2
13 % 5 = 3
14 % 5 = 4
15 % 5 = 0
16 % 5 = 1
17 % 5 = 2
18 % 5 = 3
19 % 5 = 4
20 % 5 = 0
21 % 5 = 1
22 % 5 = 2
23 % 5 = 3
24 % 5 = 4
25 % 5 = 0
26 % 5 = 1
27 % 5 = 2
28 % 5 = 3
29 % 5 = 4

Notes

* Modulus is also known as the "remainder operator." When you take the modulus of two values, the result is the remainder for the first divided by the second. You see that type of result above. For example, 8 divided by 5 leaves a remainder of 3.

* When the modulus operation divides evenly, the value zero is returned.

* A great way to use modulus is when your code needs to count every nth item in a list. That expression looks like this in C:

For example, the value %2 might be used to highlight every other item in a list.