For newer programmers, myself included, modulus is probably the most obscure operator. ie easy to understand, not always easy to find a use for. But when you see an algorithm that uses modulus, it immediately makes sense. How about a few samples where modulus works well.

For example, is a number odd or even

if(x%2 == 0)
number is even
else
its not

or the old stand by for figuring out leap year

if ((yearInt%4==0)&&!(yearInt%100==0)||(yearInt%400==0))
it's a leap year
else
it's not

what else do you guys use it for.

You can use the modulus operator to convert numbers to another base
(e.g: from decimal to octal/hexadecimal/binary/etc.) ...

Movement through a circular structure such as a circular array, degrees of rotation, days of the week, etc.

You can use the modulus operator to convert numbers to another base
(e.g: from decimal to octal/hexadecimal/binary/etc.) ...

Look at this code snippet on Daniweb ...

For algorithms that directly require modular arithmetic, such as some encryption algorithms.

For writing log messages every Nth time through a loop.

The "do something every Nth time through a loop" problem is probably where you'll see the modulus operator used most often.

The "do something every Nth time through a loop" problem is probably where you'll see the modulus operator used most often.

I generally just use the logical AND operator for that.

Well some people have better things to do than explain why their product can only be configured to use powers of two.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.