Most developers are familiar with the modulo opertor, it is often presented in an example that determines if a number is odd or even as shown in the code below taken from Testing whether a value is odd or even.
|
|
Determining if a number is odd or even is just one use case for the modulo operator. Another use case that I learn a while back is that you can use the modulo operator to set a range, a boundary if you will, allowing you to rotate the array, this is because fundamentally A mod B is between 0 and B - 1 or another way to think about it, 0 <= A < B.
For example, imagine an array of length 4 and an indexer that is incremented as we loop through the array.
|
|
As you can see from the example above, the modulo operator created a boundary between 0 and 3, this technique is known as a circular array. You can use a circular array if you are implementing pagination and need to return to the first page when all the pages have been visited.