# Arithmetic Sequences When Programming

C

##### Guest
I'm sure that most of you know what an arithmetic sequence is. An example of one of these would be: 1, 2, 3, 4, 5 etc.. This sequence's difference is 1, because every number in the sequence increases by 1. What I'm trying to do is create different sequences and then apply them to code. For example, imagine if you have the sequence: 1, 3, 5 (this sequence has a difference of 2) and you also have the enemies: a, b, c, d, e. The first number in the sequence is 1, which means that it will attack the first enemy, which is enemy a. The next number in the sequence is 3, which means that it will attack the third enemy, which is enemy c. And finally, the last number in the sequence is 5, which means that it will attack the fifth enemy, which is enemy e.

However, this complex system doesn't end here (I'm so sorry)... When the "turn" is done, this system starts again, but since the "count" starts at 5 this time, not 1 (because the sequence finished at 5 before), the difference creates a new sequence starting at 5. This means that the new sequence would be: 2, 4, 1. And this means that the enemies attacked would be b, d, and a.

How would one create a system like this? I don't really know how to make the "cycling" mechanic that makes the system create more sequences out of the difference. Sorry if this was very confusing, I tried explaining this to the best of my abilities. If you have any questions about my question feel free to ask!

R

#### rui.rosario

##### Guest
Imagine you have a variable (maxIndex) that holds the maximum value the cycle should take (in this case 5) and a variable with the increment amount (incAmount, in this case 2). You then have a variable (curIndex) which holds the current index of the sequence. Using the modulo operator (mod or %) you can make the cycle, since the modulo of a by b will always be a number from 0 to b - 1.

This means that in your case, if you want a cycle from 1 to 5 you can calculate the next step of the sequence as:

Code:
``curIndex = (curIndex + incAmount) % maxIndex;``
This however would give you a sequence from 0 to 4 (inclusive). You could then add 1 to get the desired effect:

Code:
``curIndex = ((curIndex + incAmount) % maxIndex) + 1;``
Hope it helps.

C