C Program to check if a matrix is an identity matrix


January 9, 2023, Learn eTutorial
1594

What is an identity matrix?

The Identity Matrix or Unit matrix is a Square Matrix with ones (1's ) on the Principle diagonal and zeros (0's) everywhere else. In this C program, we need to check if the given input is an identity matrix or not.

How to check for an identity matrix using the C program?

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

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 it into the variables R and C.

STEP 6: Read the elements of 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 && mat[j][i] !=0  then set flag=0 and break from the loop. Otherwise, repeat the loop with the next iteration.

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


To check for an identity matrix in C, we are using the below concepts. We recommend you learn those for a better understanding

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