For loop using the modulo

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:


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.

Just compare the two indices, and set the smaller one to ind1
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
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
This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main() {
	int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	int ind1 = 8, ind2 = 3;
	int total = 0;

	for (int i = ind1; i != ind2+1; i++) {
		i%=10;
		total += a[i];
	}
	cout<<total;
}

Edit: i do not know if the modulo can be done in the for loop step declaration
Last edited on
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];
}
1
2
3
4
5
6
7
8
9
10
const int N = 10;

for ( int i = 0; i < N; i++ )
{
	for ( int j = i, k = N; k-- != 0; j + 1 == N ? j = 0 : ++j )
	{
		std::cout << j << ' ';
	}
	std::cout << std::endl;
}


Or the inner loop can be written as

for ( int j = i, k = N; k-- != 0; j = ( j + 1 ) % N )

0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
2 3 4 5 6 7 8 9 0 1
3 4 5 6 7 8 9 0 1 2
4 5 6 7 8 9 0 1 2 3
5 6 7 8 9 0 1 2 3 4
6 7 8 9 0 1 2 3 4 5
7 8 9 0 1 2 3 4 5 6
8 9 0 1 2 3 4 5 6 7
9 0 1 2 3 4 5 6 7 8
Last edited on
Topic archived. No new replies allowed.