When do I use the modulo operator?

Question

When do I use the modulo operator?

Answer

The modulo operator (%) gives us the remainder after a division.

One common use is for telling whether a number is even or odd. Specifically, if x is even, x % 2 will always equal 0. If x is odd, x % 2 always equals 1.

Similarly, we can use it to help find every nth element (ie. by looking at x % n).

1 Like