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.

5
Contributors
6
Replies
9
Views
9 Years
Discussion Span
Last Post by thoughtcoder

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.