Matrix is identity matrix or not
C program to check if a matrix is identity matrix or not.
Identity matrix of size n is the n × n square matrix in which elements of principle (main) diagonal are ones, and the rest of the elements are zeroes. Identity matrix is also known as unit matrix.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void identity(int mat[MAX][MAX], int row)
{
int i, j, flag;
flag = 0;
for(i=0;i<row;i++)
{
for(j=0;j<row;j++)
{
if((i==j) && mat[i][j]!=1)
{
flag = 1;
}
else if(i!=j && mat[i][j]!=0)
{
flag = 1;
}
}
}
if(flag == 0)
{
printf("\nMatrix is identity matrix");
}
else
{
printf("\nMatrix is not an identity matrix");
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows or columns of the square matrix\t:");
scanf("%d",&row);
col = row;
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
identity(mat, row);
getch();
}
Output
********** Run1 **********
Enter the number of rows or columns of the square matrix :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :0
Element [0][2] :0
Element [0][3] :0
Element [1][0] :0
Element [1][1] :1
Element [1][2] :0
Element [1][3] :0
Element [2][0] :0
Element [2][1] :0
Element [2][2] :1
Element [2][3] :0
Element [3][0] :0
Element [3][1] :0
Element [3][2] :0
Element [3][3] :1
Matrix entered is
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Matrix is identity matrix
********** Run2 **********
Enter the number of rows or columns of the square matrix :3
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :0
Element [0][2] :4
Element [1][0] :0
Element [1][1] :1
Element [1][2] :0
Element [2][0] :0
Element [2][1] :0
Element [2][2] :1
Matrix entered is
1 0 4
0 1 0
0 0 1
Matrix is not an identity matrix