# Bidirectional loop? (Increase/decrease depending on values)

• 01-07-2011
BlueGooGames
Bidirectional loop? (Increase/decrease depending on values)
I have two values: x_start and x_end. From time to time any value can be the highest.
How can I make a single for or while-loop to iterate through x in any directions to count either from x_start to x_end or the other way around?

Of course I can do it with an if statement and two for loops, but since I'm gonna fill the loop with lots of stuff, I'd like to smack it into one loop. Is that possible? :)

Code:

```int step = 2;    // Can vary int x_start = 10; // This could be 20 int x_end = 20;  // And this could be 10 for (int x = x_start; x<=x_end; x+=step) {   printf ("x = %d\n", x); }```
• 01-07-2011
anduril462
Yep. Have a second set of variables, called smallest and largest. Use the classic
Code:

```int smallest = x_start < x_end ? x_start : x_end; // similar for largest for (int x = smallest; x <= largest; x += step) ...```
• 01-07-2011
tabstop
Or, if you have to start at start and stop at end (regardless of whether that's up or down), then you do the same sort of ?: trickery, except making step positive or negative.
• 01-07-2011
iMalc
Either make step negative when x_end < x_start, or put the body of the loop into its own function, and just go with two loops.
• 01-08-2011
BlueGooGames
Thanks a lot, that worked out great. Have coded PHP for 10 years, never had to use that before. But now when coding a game, that was handy :)