0

Sorry, the title isn't the best, but I can't think of he name for what I am doing.

I have an array of colours that I use to render a bar chart. The array contains 15 (for now) items (colours). (index 0 to 14)

I am trying to create a method that accepts an integer value, and returns an number between 0 and 14 base on it.

For example, if I pass in 3, it will give me the 3rd item in the array of 15 available items. But if I pass in 16 (Out of bounds of the array length), it must return item 0 (The first item). If I pass in 17, it returns 1. So, it loops around.

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,0,1,2,3... etc.

Is there a C# operator to do this, or a simple method I can create? I was trying to see if I could use mod, but I can't wrap my head around a nice efficient way to achieve this.

Craig
  • 18,074
  • 38
  • 147
  • 248
  • 1
    Yep, the modulo operator is what you need. `16 % 14 -> 2` –  Jan 08 '20 at 20:46
  • Thanks @Amy - I was doing it the wrong way around. Thanks very much. If you make an answer, I'll accept it. – Craig Jan 08 '20 at 20:49
  • 3
    @Amy: Note that the `%` operator is the *remainder* operator, which is subtly different. Most people think of the modulus as being non-negative, but in C# we define `x%y` such that `(x/y)*y+(x%y) == x` is true for integer x and non-zero integer y. Add to that the fact that `x/y` rounds towards zero and that `(-x)/y == -(x/y)` and `x/(-y)`. These facts imply that there are situations in which the remainder is negative. – Eric Lippert Jan 08 '20 at 21:47

0 Answers0