# Inverting index code

I have a piece of code at the moment that indexes through a series of displays using the Switch/Case method and a simple debounced push button.
At the moment I have it setup so that when it reaches case 11 it resets to case 0, however, I've been trying to get my head around a 'simple' way to make in go backwards and forwards through the index instead..

To try and clarify my question, using my current code, when I press the push button I get:

Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3.... etc...

What I would like to achieve is:

Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4... etc..

I've been playing with having a boolean flag that starts true and therefore a button press causes button_index++, when button_index > 10 set the flag to false so therefore a button press causes button_index-- and so on and so forth..

I'm just struggling to work out how to make it loop continuously..

Use a signed variable as an increment value. When you reach 11 change the increment to -1, when it gets back to 0 make it 1 again.

Have an index variable and an increment variable. Start the index at 0 and the increment at 1. Add the increment to index at each stage. Then

``````if (index < 0 || index > 10)
{
increment = increment * -1;
}
``````

Or cheat

If you reach 11 you make it -9 (so a singed variable type needed) and instead of a switch with that value you do

``````switch(abs(value))
``````

Thanks!

I'll try the increment = increment * -1 later, thats the sort of simple solution I felt sure existing, but I was just over thinking it..

I'll try the increment = increment * -1

Or even `increment = -increment;`

Naaah - no need to increment/decrement. Just fold the sequence in the middle:

``````int pushCount = 0;
int index;

void onButtonPush() {
if(++pushCount >= 20) pushCount = 0; // cycle from 0 to 19

index = (pushcount < 10) ? pushCount : 20 - pushCount; // 0->9 and then 10->1
}
``````

Mm, you made that look short with inline if-else but mm. Find the incrementFlag option nicer. Or actually like the cheat use of signed variable type the most

``````void onButtonPush(){
pushCounter++;
if(pushCounter > HighestNumber){
pushCounter = -HighestNumber + 1;
}
}

and just use abs(pushCounter) value :D Now all info is stored in a single variable :)
``````