C# Modulus Operator

I can write the program

int a = 3;
int b = 4;

Console.WriteLine(a % b);

The answer I get is 3. How does 3 mod 4 = 3???

I can't figure out how this is getting computed this way.

4

7 Answers

I wasn't quite sure what to expect, but I couldn't figure out how the remainder was 3.

So you have 3 cookies, and you want to divide them equally between 4 people.

Because there are more people than cookies, nobody gets a cookie (quotient = 0) and you've got a remainder of 3 cookies for yourself. :)

5

Because the remainder of 3 / 4 = 3.

7

3 mod 4 is the remainder when 3 is divided by 4.

In this case, 4 goes into 3 zero times with a remainder of 3.

I found the answer confusing and misleading.....

Modulus is what is left over IN THE FIRST NUMBER after dividing the second into it as many times as possible.

1 % 1 = 0 because after dividing 1 into 1, one time, there's nothing left
2 % 1 = 0 because after dividing 1 into 2, two times, there's nothing left
1 % 2 = 1 because 2 won't go into 1, so 1 is left

I already think that the user may have understood the answers. Because there are so many good programmer.. in simple wording % tells you the reminder after dividing with your own integer.

e.g.

int a = int.Parse(Console.ReadLine());
int b = a % 2;

Now your input 13, it will give 1, because after diving 13 by 2 remainder is 1 in simple mathematics. Hope you got that.

1

As explained by others, but if you don't want to use the "mod" operator. Here is the equation to figure out the remainder of "a" divided by "n"

a-(n* int(a/n))

Another "as explained by others", but if you're curious about several more ways to do modulus (or use an alternative method), you can read this article which benchmarks a few different ways.

Basically, the fastest way is the good old fashioned modulus operator, similar to:

if (x % threshold == some_value)
{
    //do whatever you need to
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest