tdammon
tdammon

Reputation: 589

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.

Upvotes: 1

Views: 615

Answers (4)

bhow
bhow

Reputation: 88

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

Upvotes: 2

Jason
Jason

Reputation: 11822

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

Upvotes: 0

serhiyb
serhiyb

Reputation: 4833

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;

Upvotes: 2

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?

Upvotes: 1

Related Questions