0

Here's my example code in C:

int x, y;
x = 7 % 10;
y = 10 % 7;
printf("%d, %d", x, y);

It prints: 7, 3

I understand 10 % 7 = 3.

I don't understand 7 % 10 = 7.

I've tried the same code using float variable and got the same answer. How does mod work when the divisor is larger than the dividend? I would really like to fundamentally understand how to use this operator.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alex
  • 91
  • 1
  • 2
  • 8
  • 1
    Forgive me for asking but have you done ANY research on your own? – klutt Nov 04 '17 at 20:15
  • 1
    `7 / 10` is `0`. The remainder is `7`. So `7 % 10` is `7`. – Tom Karzes Nov 04 '17 at 20:48
  • Also keep in mind that, for positive integers `a` and `b`, `(a + b) % b` is the same as `a % b`. In other words, you can keep subtracting `b` until the result is less than `b`, and that's the remainder. – Tom Karzes Nov 04 '17 at 20:49

3 Answers3

4

Modulus returns the remainder after division.

7 % 10 = 7 because 7 / 10 < 1, e.g. 10 does not fit even once in seven. So the entire value of 7 becomes the remainder.

negacao
  • 1,244
  • 8
  • 17
3

10 % 7 = 3 is so because 10 / 7 is 1. 1 * 7 + 3 = 10, hence 3 is the remainder.

7 % 10 = 7 is so because 7 / 10 is 0. 0 * 10 + 7 = 7, hence 7 is the remainder.

cnettel
  • 1,024
  • 5
  • 7
  • @arosenfeld2003 Note this answer works with negative numbers too. Try a few examples with negative numbers. :) – MFisherKDX Nov 04 '17 at 20:20
1

C11 6.5.5 Multiplicative operators

Paragraph 5:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

Paragraph 6:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

So, here 7 divided by 10 is 0 with a remainder of 7.

msc
  • 33,420
  • 29
  • 119
  • 214
  • @Downvoter what am I miss here?? – msc Nov 04 '17 at 20:35
  • 1
    I just upvoted all the other answers. Not sure why we all got downvoted. – negacao Nov 04 '17 at 20:46
  • probably because that's an obvious triplicate. Basic C questions like this _have_ an answer on stack overflow. People tend to downvote answers to trivial questions. I don't (I prefer downvoting questions with no research), but I can understand. – Jean-François Fabre Nov 04 '17 at 21:01