C Program to Check Identity Matrix

programming

Problem: Write a C program to check whether the given matrix is an identity matrix or not.

In linear algebra, the identity matrix (sometimes ambiguously called a unit matrix) of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere.

Identity Matrix

Steps to check identity matrix in C:

  1. Input a matrix.
  2. Iterate through the elements of the matrix:
    • For i==j check if matrix[i][i] != 1 and for i!=j check if matrix[i][j] != 0:
      • If any element satisfies any of the above conditions then the input matrix is not an identity matrix.
  3. Otherwise, the matrix is an identity matrix.

Here is the implementation of the steps in C:

#include <stdio.h>
#include <stdbool.h>
 
int main()
{
  //Flag to decide whether matrix is identity or not
  bool flag =true;

  //order of the matrix
  const int n=3;
  
  //Input matrix
  int matrix[n][n] = {{1, 0, 0},
                      {0, 1, 0},
                      {0, 0, 1}};

  //Iterate through the left diagonal elements
  for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
      //left diagonal element should be 1
      if(i==j && matrix[i][j] != 1){
        flag = false;
        break;
      }
      //non diagonal element should be 0
      else if(i!=j &&matrix[i][j] != 0){
        flag = false;
        break;
      }
    }
  }

  if(flag==true)       
    printf("Identity Matrix \n");
  else
    printf("Not an Identity Matrix \n");

  return 0;
}

Output:

Identity Matrix

In the program, we have used a 2D array to represent the matrix and for loops to iterate through the matrix elements.

In this programming example, we learned to check the identity matrix in C using the ‘for’ loop and ‘if’ condition.

Leave a Reply

Your email address will not be published. Required fields are marked *