C Program to check if a matrix is an identity matrix

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is an identity matrix?

Here in this C program, we need to check whether the given Matrix is an identity matrix or not, for that we need to know what is an Identity Matrix. The Identity Matrix or Unit Matrix of size 'n' is the n × n Square Matrix with ones on the Principle diagonal and zeros everywhere else. 

The logic of this C program is first to declare the Matrix A.Then read the Order of the Matrix into R and C.Then read the elements of the Matrix using for loop. Then display the given Matrix. Then check each element of the Array not equal to 1 and not equal to 0, if True then set Flag=1 and Exit from the loop. If flag=1 then displays it is an Identity Matrix, otherwise, say it is not an Identity Matrix.


STEP 1: Include the header files to use the built-in Functions in the C program.

STEP 2: Declare the Matrix A of an integer Data type.

STEP 3: Declare the variable i, j, R, C, flag.

STEP 4: Set flag=1.

STEP 5: Read the order of Matrix A into the variables R and C.

STEP 6: Set i=0.

STEP 7: Check i

STEP 8: Read the elements of the Matrix by using the for loop with the condition 'i'.

STEP 9: Display the input Matrix as the elements of A using for loop.

STEP 10: Set j=0.

STEP 11: Check j

STEP 12: Check if A[i][j] != 1 && A[j][i] !=0  then set flag=0 and break from the loop.Otherwise increment j by one and repeate step 16.

STEP 13: Increment 'i' by one repeat step 14.

STEP 14: If flag==1 then displays, it is an identity matrix.

STEP 15: If flag==0, then display it as not an identity matrix.

C Source Code

                                          #include <stdio.h>

void main() {
  int A[10][10];
  int i, j, R, C, flag = 1;
  printf("Enter the order of the matrix A\n"); /* enter the order of the matrix */
  scanf("%d %d", & R, & C);
  printf("Enter the elements of matrix A\n");
  for (i = 0; i < R; i++) {
    for (j = 0; j < C; j++) {
      scanf("%d", & A[i][j]);
  printf("MATRIX A is\n"); /* printing the matrix input by the user */
  for (i = 0; i < R; i++) {
    for (j = 0; j < C; j++) {
      printf("%d", A[i][j]);
  for (i = 0; i < R; i++) /* Check for unit (or identity) matrix */ {
    for (j = 0; j < C; j++) {
      if (A[i][j] != 1 && A[j][i] != 0) {
        flag = 0;
  if (flag == 1)
    printf("It is identity matrix\n");
    printf("It is not a identity matrix\n");


Run 1

Enter the order of the matrix A
2* 2

Enter the elements of matrix A
2 2
1 2

2  2
1  2

It is not a identity matrix
Run 2

Enter the order of the matrix A
2 *2

Enter the elements of matrix A
1 0
0 1

1  0
0  1
It is identity matrix