Arijit Karali
Arijit Karali

Reputation: 69

Else statement is executed even if 'If statement' seemed to be true

The problem is to find symmetricity in a matrix of characters(char logo[N][N]) where logo contains some characters(only 0 or 1).

Note that, in the output of the code, once i get all the 4 logo elements as 0 i.e. if(0==0==0==0), then else code is also executed.

I have implemented the symmetricity checking code and found that the only problem is occurring at the given block of code where else block is executed and it gives wrong result (NO).

code snippet:(N is size of the square matrix)

int YES=1;
for(j=N-1;j>((N-1)>>1);j--) /* symmetricity condition particular to the problem*/
    {
        for(k=0;k<((N-1)>>1);k++)
        {
            printf("%c %c %c %c\n",logo[j][k],logo[N-1-j][k],logo[j][N-1-k],logo[N-1-j][N-1-k]); // used this line for debugging
            if(logo[j][k]==logo[N-1-j][k]==logo[j][N-1-k]==logo[N-1-j][N-1-k])continue;   //checking symmetricity
            else  // here else is executed when all 4 logo elements are 0
            {
                YES=0;
                break;
            }
        }
    }
    (YES==1)?printf("YES\n"):printf("NO\n");

I expect the output to be "YES" as every time the 4 logo element is checked found to be same (1111 or 0000) but here you can see result is NO after i get 4 zeros.

1st line is number of test case, second line is N, then N*N matrix OUTPUT :1st line is number of test case, second line is N, then N*N matrix

you can see when all logo elements are 1111 then it reenters loop but after 0000 it breaks and prints NO.

Upvotes: 0

Views: 113

Answers (2)

Dominique
Dominique

Reputation: 17493

Replace your if-statement by this:

if((logo[j][k]==logo[N-1-j][k]) && 
   (logo[N-1-j][k]==logo[j][N-1-k]) &&
   (logo[j][N-1-k]==logo[N-1-j][N-1-k]))
  continue;   //checking symmetricity

Current implementation does the following:

logo[j][k]==logo[N-1-j][k] // returns TRUE
==logo[j][N-1-k]           // returns FALSE (I imagine that logo[j][N-1-k] does not equal TRUE
==logo[N-1-j][N-1-k]       // returns FALSE (I imagine that logo[N-1-j][N-1-k] does not equal FALSE

Upvotes: 1

alinsoar
alinsoar

Reputation: 15793

logo[j][k]==logo[N-1-j][k]==logo[j][N-1-k]

== is left associative. It returns 0 or 1. This means that the 2nd == will compare either 0 or 1 with logo[j][N-1-k]. You do not want that, so you need to insert correct operands by duplicating some of them and using && operator.

Upvotes: 1

Related Questions