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:
1 2 3 4 5 6 7 8
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ind1 = 3, ind2 = 8;
int total = 0;
for (int i = ind1; i <= ind2; i++)
total += a[i];
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.
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
This is what i've done. Thanks for your help...... this seems to work for both instances.
1 2 3 4 5 6 7 8 9 10 11 12
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int ind1 = 8, ind2 = 3;
int total = 0;
int num = (ind1 < ind2) ? ind2 - ind1 + 1 : 10 - ind1 + ind2 + 1;
for (int i = 0; i < num; i++)
{
int index = (i + ind1) % 10;
total += a[index];
}