| jazpearson (47) | |||
|
My brain doesn't seem to be working at all today. Here's my problem. Imagine having an array of integers, but i want to add up these integers from a pair of indices. So, let's imagine we have an integer array containing 10 items, and the two indices are given by 3 and 8. To do the sum, we would have:
Of course, this is simple. However, what happens if i want to go from indices of 8 to 3? That is i want to calculate 9+10+1+2+3+4........ I could write two for loops to handle this situation, but i'm sure there's a way to do this in one loop with the help of the modulo. I just can't remember. | |||
|
|
|||
| Script Coder (352) | |
| Just compare the two indices, and set the smaller one to ind1 | |
|
|
|
| jazpearson (47) | |
|
That won't do what i want though. That would add up the values as before: 4+5+6+7+8+9 I want: 9+10+1+2+3+4 | |
|
|
|
| Script Coder (352) | |
| I see, then you would have to inside your for loop check to see if you are one the last number and if so set i=0, or always modulo i by the length of the array | |
|
Last edited on
|
|
| Script Coder (352) | |||
This is my code:
Edit: i do not know if the modulo can be done in the for loop step declaration | |||
|
Last edited on
|
|||
| jazpearson (47) | |||
This is what i've done. Thanks for your help...... this seems to work for both instances.
| |||
|
|
|||
| vlad from moscow (3112) | ||||
Or the inner loop can be written as for ( int j = i, k = N; k-- != 0; j = ( j + 1 ) % N )
| ||||
|
Last edited on
|
||||