-5

How to make modulus operation in C language?

Please read my code below.

#include <stdio.h>

int main(void)
{       
    int i = 100;

    printf("%d\n", i%100);
    printf("%d\n", i%240);
    printf("%d\n", i%40);
    printf("%d\n", i%10);


    return 0;
}

The result is

$ ./modulus
0
100
20
0

Please tell me how to use it correctly.

EDIT

Sorry I did a mistake in code. the division should come otherside like in below code.

printf("%d\n", 100%i);
printf("%d\n", 240%i);
printf("%d\n", 40%i);
printf("%d\n", 10%i);

What I was expecting was to get the 0 when the value is multiplication of 100;

I am sorry for the mistake. But guys, please undo my downvotes.

fSazy
  • 326
  • 1
  • 4
  • 16

3 Answers3

1

The result of a modulo division is the remainder of an integer division of the given numbers ( on the positive scale).

That means:

100 / 100 = 1, remainder 0
=> 100 mod 100 = 0

100 / 240 = 0, remainder 100
=> 100 mod 240 = 100

100 / 40 = 2, remainder 20
=> 100 mod 40 = 20

100 / 10 = 10, remainder 0
=> 100 mod 10 = 0
Sadique
  • 22,572
  • 7
  • 65
  • 91
  • *"The result of a modulo division is the remainder of an integer division of the given numbers."* ---> [modulus and remainder are not the same](http://www.sitecrafting.com/blog/modulus-remainder) – Grijesh Chauhan Mar 19 '14 at 09:58
  • @GrijeshChauhan - Thanks :-) - added `on the positive scale` – Sadique Mar 19 '14 at 10:01
  • Add trick for [negative](http://stackoverflow.com/questions/19264015/modulo-of-a-negative-number) also, Check related Q&A also I am not sure that is correct. – Grijesh Chauhan Mar 19 '14 at 10:02
1

Well, it works correctly. What have you expected to see?

Modulos operator (the implementation of the modulo operation), gets you the division remainder. For example:

a % b = c

Can be rewritten as a = b * d + c, where a, b, c, d are integers.

So, 100 % 40 = 20 because 100 = 40 * 2 + 20

Paul92
  • 8,827
  • 1
  • 23
  • 37
0

the output you are getting is correct. The modulus operator returns the remainder when you perform integer division of two numbers.

In your case

  • 100 mod 100 = 0 as 100 = 100*1 + 0
  • 100 mod 240 = 100 as 100 = 240*0 + 100
  • 100 mod 40 = 20 as 100 = 40*2 + 20
  • 100 mod 10 = 10 as 100 = 10*10 + 0

Hope it helps :)

Meeth
  • 81
  • 7