Modulus Operator
#include <stdio.h>
main()
{
int a, b, q, r;
printf(" a b a/b a%%b\n");
while (scanf("%d%d", &a, &b) != EOF) {
q = a / b; /* quotient */
r = a % b; /* remainder */
printf("%4d %5d %5d %5d\n",
a, b, q, r);
}
}
This is the program
mod.c
.
a.out < in.dat
a b a/b a%b
10 3 3 1
3 10 0 3
-10 3 -3 -1
10 -3 -3 1
-10 -3 3 -1
(in.dat contains a list of the first two columns of numbers a and b)
It is always true that
a = q*b + r
with |r|<|b|, b? 0.
Next slide
Back to first slide
View graphic version