简体   繁体   中英

How can I make an if statement that is true only if it works for all i's in a loop?

I have a 2D array of consecutive integers. My code should test if the integers in a row are all in order. I want to write an if statement that evaluates to true only if it is true for all the i's and j's in the loop.

for(int i=0; i<4;i++) {
    for(int j=0; j<13;j++) {
        if(board[i][j]+1 == board[i][j+1]) {
            return true;
        }
    }
}

Again, the if statement should only evaluate to true if the conditions are true for the entire loop.

You can instead check inequality and return false. If you make it all the way through your loop without returning false, return true.

for(int i=0; i<4;i++) {
    for(int j=0; j<13;j++) {
        if(board[i][j]+1 != board[i][j+1]) {
            return false;
        }
    }
}
return true;

Why don't you use a boolean variable. If in any of the iterations of i and j the condition is not met, you invert the value of you variable, and once the for loop is finished you check your variable?

for(int i=0; i<4;i++) {
    for(int j=0; j<13;j++) {
        if(board[i][j]+1 != board[i][j+1]) {  // if any item is not the same
            return false;
        }
    }
}
return true;  // if we get here, all items were the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM