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

How to check if a matrix is an identity matrix in C

The logic of this C program is first to declare the Matrix. 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.

ALGORITHM

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

STEP 2: Declare the Matrix mat 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 the Matrix into the variables R and C.

STEP 6: Read the elements of the Matrix mat[i][j] by using nested for loop with the conditions i < R, j < C

STEP 7: Display the input Matrix as the elements of mat using for loop

STEP 8: Using nested for loop with the conditions i < R, j < C, check if mat[i][j] != 1 && A[j][i] !=0  then set flag=0 and break from the loop.Otherwise repeat the loop with next iteration.

STEP 9: Now check If flag==1 then display, it is an identity matrix,else display it is not an identity matrix.

C Source Code

                                          #include <stdio.h>

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

OUTPUT

Run 1

Enter the order of the matrix
2 2

Enter the elements of matrix
2 2
1 2

MATRIX is
2  2
1  2

It is not an identity matrix
Run 2

Enter the order of the matrix
2 2

Enter the elements of matrix
1 0
0 1

MATRIX is
1  0
0  1
It is an identity matrix