Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement within FOR loop statement?

I want to put if statements within my for loop checking parameters but I don't know how to do it, I want this so I don't have to duplicate my code and make it huge, redundant and messy.

This is what I am trying to do

for( int i = elevator1CurrentStatus.floorNumber; if(boundary == 9) i<boundary else i>boundary ;i+=i+countDirection){

//Code Here 

}

How would I implement this? Basically I want the test statement stating whether to count up or down to depend on a variable and select which direction based on that variable. Count direction is implemented earlier and is either +1 or -1. for( int i = elevator1CurrentStatus.floorNumber; (if(boundary == 9) iboundary;) ;i+=i+countDirection)

 for( int i = elevator1CurrentStatus.floorNumber; (if(boundary == 9) i<boundary else i>boundary) ;i+=i+countDirection)
like image 890
user2076774 Avatar asked Jun 01 '26 18:06

user2076774


2 Answers

Use ternary operator:

for(int i = elevator1CurrentStatus.floorNumber; 
    boundary == 9 ? i < boundary : i > boundary; 
    i += i + countDirection) {

//Code Here 

}

But I would move the condition to separate function/method to improve readability.

like image 144
nameless Avatar answered Jun 03 '26 10:06

nameless


I will suggest to put the condition in a separate function. It will make it more readable. Try not to inline complex conditions. Also, you can now use any multi-level if-else, switch case or any other operation that returns a boolean.

Here is what you can do:

bool conditionCheck(int i, int boundary) {
        if (boundary == 9) {
            return i < boundary;
        } else {
            return i > boundary;
        }
    }

int main(int argc, char *argv[]) {
        int boundary = 10;
        int i = 0;
        for (i = 0; conditionCheck(i, boundary); i++) {

        }

    }
like image 37
Ankit Avatar answered Jun 03 '26 10:06

Ankit