econsteve
econsteve

Reputation: 55

If statement not evaluating as expected

I have no clue why this is not evaluating the way I expect it to. I apologize if this is obvious. The problem lies in the following if statement:

if (count == cordX && i == cordY) {

It lies within a larger while loop:

while (count < 10) {
    printf("0%d", count);
    for (i=0; i < 10; i++) {
        if (count == cordX && i == cordY) {
            x[i] = 1;
            printf("|%d", x[i]);
        } else {
            printf("|%d", x[i]);
        }
    }
    count++;
    printf("|");
    printf("\n");
    printf("Count : %d\n", count);
}

Now this will print out a grid of columns and rows. The first column of every row prints out as "1" despite the fact that cordX is equal "0" and count gets incremented every time the loop runs. So it must only be evaluating the " i == cordY" part of the if statement, as cordY also equals "0". Here is a pic of the output to make it more clear than my explanation:

Output: As you can see "count" is clearly incrementing

Upvotes: 0

Views: 69

Answers (1)

abligh
abligh

Reputation: 25119

Your problem is not in the test, it's a logical issue. On the first iteration around, your condition is met, and thus you set x[i] to 1; from the debug output we can see this is when i is 0, so x[0] is set to 1.

On the next iteration of the while loop, however, x[0] is still 1, so it will still print a 1 in the first column. Insert an x[i]=0 after the else to fix it, though why you are storing the values in an array in the first place is a bit of a puzzle.

Upvotes: 2

Related Questions