ARRAY

Hi guys

I have a small issue in C++.
I have an array arr[] = {1,2,3,4,5,6,7,8,9,10}
I need to have a loop where I start the loop from start of the array( i.e arr[1])
print all the elements till the end of the array ( i.e arr[9] )
The moment it reaches the end of the array, it shud traverse back till arr[1].
This loop should be infinite. going from arr[1] - arr[9] and vice versa
Use a bool variable that indicates whether you're currently going "up" or "down" and reverse it whenever you reach either end.
the array is zero based not 1 based. So you want to start with array[0]. In this case you might as well just create a SIZE constant to use in the creation of the array which can also be used in the loop so that you know when to start counting back down. So you have a continuous while loop and two inner for loops. One counts forward and the other counts backward.
There's actually a pretty graceful way to accomplish this with a direction variable.

1
2
3
4
5
6
7
8
//-1 initial value for direction, because it will be negated on the first iteration
for (int i = 0, dir = -1;; i += dir) { //every step, add the dir variable to i
    //reverse dir on an edge case 
    //you could do this in the increment part of the loop too at the cost of all readability 
    //(it's not even that readable as it is, it might be better in an if statement)
    dir *= (i <= 0 || i >= ARR_MAX) ? -1 : 1; 
    //loop body...
}
Last edited on
Topic archived. No new replies allowed.