[Solved] Checking an identity matrix in C


There are several errors. For example you use variable n before its initialization

matrix=(int**)malloc(n*sizeof(int*));
scanf("%d",&n);

There must be

scanf("%d",&n);
matrix=(int**)malloc(n*sizeof(int*));

You never set variable flag to 1. So it always has value equal to 0 independing of the matrix values.

The break statement in this loop

    for(j=0;j<n;j++)
    {
        if(matrix[i][j]!=1 && matrix[j][i]!=0)
            flag=0;
        break;
    }

have to be inside the compound statement of the if statement. Otherwise it has no sense.

For example the loops can look the following way

flag = 1;
for ( i = 0; flag && i < n; i++ )
{
    for ( j = 0; flag && j < n; j++ )
    {
        if ( matrix[i][j]!=1 && matrix[j][i]!=0 ) flag = 0;
    }
}

Take into account that blank lines between C constructions are very important elements of the code. They make the code more clear and readable.

2

solved Checking an identity matrix in C