# Thread: looping a variable within a loop.

1. ## looping a variable within a loop.

This is probably a very basic question but I just can't work out how to find the answer after trying more then a few times.

How can I create a variable so that it loops within a certain range, even if I add or subtract more then the range?

Say I want "int i" to be equal to 0-3, but in my code I have several nested loops and I want to increment "i" several times? I want it to return to 0 if I increment past 3, and i want it to go to 3 if I decrement below 0.

i've used
Code:
` if (i>3){i=0};`
at the end of a loop if it increments just once once, but what if I increment it 3 or 4 times in the loop? Also that doesn't work for the decrement condition. There must be an easier way then having an if statement after each increment?

something like
Code:
```
a_array[i++] = b_array[i];
if (i>2){i=0};
a_array[i++] = b_array[i];
if (i>2){i=0};
a_array[i++] = b_array[i];
if (i>2){i=0};```
This is just awful, I suspect there's an easy answer but no luck finding it.

Out of desperation I did it once using another array like a[0,1,2,3,0,1,2,3,0,1,2,3], this lets me increment a few times before having to use an "if" statement like above, but I suspect this would get laughed at too.

Sorry for the noob question, even just a pointer to a tutorial or a hint what to google would be great, thanks very much. 2. You should make it into some sort of loop to make it less awful. As far as I know you are just repeating the a_array[i++] = b_array[i]; statement over and over. 3. The example I gave is a simplified version of what I'm trying to do.. it's already loops within loops which are confusing me enough, if you're saying this is not possible I'll just have to keep straining my brain. I just thought there might be a simple trick to do this kind of thing which would simplify things for me considerably.. If it's not possible I'm obviously on the wrong track, by the sounds of it.

I just thought maybe it could be done with modulus or something... 4. wraparound numbers and modulus seems to be the terms I needed to search for,

Coding Practices – The Modulus Operator.. « WatchHogStories

Code:
```    // increment index & return the item in the array
i++;
if (i >= maxNumValues) i = 0;
return foo[i];

We can now substitute it for something like this

// increment index & return the item in the array
return foo[ (i++)  %  maxNumValues ];```
Thanks. Popular pages Recent additions 