Check the Identity matrix with C.
#include <stdio.h>
int main()
{
int A[3][3];
int row, col, isIdentity;
/* Input elements in matrix from user */
printf("Enter elements in matrix of 3 3x3: \n");
for (row = 0; row < 3; row++)
{
for (col = 0; col < 3; col++)
{
scanf("%d", &A[row][col]);
}
}
/* Check whether it is Identity matrix or not */
isIdentity = 1;
for (row = 0; row < 3; row++)
{
for (col = 0; col < 3; col++)
{
if (row == col && A[row][col] != 1)
{
/* If elements of main diagonal is not equal to 1 */
isIdentity = 0;
}
else if (row != col && A[row][col] != 0)
{
/* If other elements than main diagonal is not equal to 0 */
isIdentity = 0;
}
}
}
/* If it is an Identity matrix */
if (isIdentity == 1)
{
printf("\nThe given matrix is an Identity Matrix.\n");
/*
* Print the Identity matrix
*/
for (row = 0; row < 3; row++)
{
for (col = 0; col < 3; col++)
{
printf("%d ", A[row][col]);
}
printf("\n");
}
}
else
{
printf("The given matrix is not Identity Matrix");
}
return 0;
}
Output
Enter elements in matrix of size 3x3 :
1 0 0
0 1 0
0 0 1
The given matrix is an Identity Matrix.
1 0 0
0 1 0
0 0 1
0 Comments