Pages

Sunday, 12 July 2015

Check identity matrix

C Program to Check if a given Matrix is an Identity Matrix


Coding:
#include<stdio.h>
#include<stdlib.h>
int main()
{
      int **a,row,col,i,j,flag=0;
      printf("Please enter the total number of rows & columns of squre matrix:");
      scanf("%d%d",&row,&col);
      if(row==col){
      a=(int**)malloc(row*sizeof(int));
      for(i=0;i<row;i++)
        a[i]=(int*)malloc(col*sizeof(int));
      printf("Please enter the elements:\n");
      for(i=0;i<row;i++)
        for(j=0;j<col;j++)
            scanf("%d",&a[i][j]);
      printf("Matrix elements before transforme:");
      for(i=0;i<row;i++)
      {
        printf("\n");
        for(j=0;j<col;j++)
        {
            printf("%d ",a[i][j]);
        }
      }
      for(i=0;i<row;i++)
      {
        for(j=0;j<col;j++)
        {
            if((i==j && a[i][j]!=1)||(i!=j && a[i][j]!=0))
            {
                flag=1;
                break;
            }
        }
      }
      if(flag==0)
        printf("\nThis is an identity matrix");
      else
        printf("\nThis is not an identity matrix");
     }
      else
        printf("It is not a square matrix");
      return 0;
}

Output:

Please enter the total number of rows & columns of squre matrix:3 3
Please enter the elements:
1 0 1
0 1 0
0 0 1
Matrix elements before transform:
1 0 1
0 1 0
0 0 1
This is not an identity matrix