Question

I want to perform a check for the elements in a list from range CONST to X, in which CONST can be viewed as a mid point, and X could be any number from range 0 to the length of the list.

The first thought I have is this:

if(x>CONST) {
    for(int i=CONST; i<=x; i++){
        // Code here.
    }
} else {
    for(int i=CONST; i>=x; i--){
        // Code here.
    }
}

But I find this a bit ugly.

Is there a good way to do this without using if statement to check whether the X is greater/smaller than CONST?

Was it helpful?

Solution

You could break out the iteration into a static function. Not as efficient as i++ or i-- though.

static int it(int i, int CONST, int X) { return X-CONST >= 0 ? i+1 : i-1; }

for(int i = CONST; i != X; i = it(i,CONST,X) ) { ... }

OTHER TIPS

You can use ternary operators to make your if statements inside your for loop but that's probably more unreadable.

for(int i=CONST; x>CONST ? i<=x : i>=x; i += x>CONST ? 1 : -1) {

} 

You could try the following

int high = x>CONST?x:CONST; //sets the upper bound
int low  = x<CONST?x:CONST; //sets the lower bound
for(int i=low; i<=high; i++){
    ...
}

This depends if you care which order you iterate through the list.

Here is a different version which starts at const and goes to x.

int inc = x<CONST?-1:1;
for(int i=CONST; i!=x + inc; i+=inc){
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top