Home »
C programs »
C two-dimensional arrays programs
C program to check a given matrix is an identity matrix or not
Here, we are going to learn how to check whether a given matrix is an identity matrix or not in C programming language?
Submitted by Nidhi, on July 13, 2021
The identity matrix of size n is the n x n square matrix with ones on the main diagonal and zeros elsewhere.
Problem statement
Given a matrix, we have to check whether the matrix is an identity matrix or not using C program.
Checking a given matrix is an identity matrix or not
The source code to check a given matrix is an identity matrix or not is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
C program to check a given matrix is an identity matrix or not
// C program to check a given matrix is an identity matrix or not
#include <stdio.h>
int isIdentityMatrix(int Matrix[][3])
{
int flag = 0;
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (i == j && Matrix[i][j] != 1) {
flag = -1;
break;
}
else if (i != j && Matrix[i][j] != 0) {
flag = -1;
break;
}
}
}
return flag;
}
int main(void)
{
int Matrix1[3][3] = {
{ 1, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 }
};
int Matrix2[3][3] = {
{ 1, 0, 0 },
{ 0, 1, 1 },
{ 0, 0, 1 }
};
if (isIdentityMatrix(Matrix1) == 0)
printf("Matrix1 is an IDENTITY MATRIX\n");
else
printf("Matrix1 is NOT an identity matrix\n");
if (isIdentityMatrix(Matrix2) == 0)
printf("Matrix2 is an IDENTITY MATRIX\n");
else
printf("Matrix2 is NOT an identity matrix\n");
return 0;
}
Output
Matrix1 is an IDENTITY MATRIX
Matrix2 is NOT an identity matrix
Explanation
In the above program, we created two functions isIdentityMatrix() and main() function. The isIdentityMatrix() function is a user defined function, it is used to check a matrix is identity matrix or not.
In the main() function, we created two matrices Matrix1, Matrix2. Then we checked matrices are identity matrices or not using the isIdentityMatrix() function and then we printed the appropriate message on the console screen.
C Two-dimensional Arrays Programs »