Question
Program to determine whether a given matrix is an identity matrix.
A matrix is said to be the identity matrix if it is the square matrix in which elements of principle diagonal are ones, and the rest of the elements are zeroes.
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
MATRIX IS AN IDENTITY MATRIX
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class identityMatrix
{
public static void main(String[] args)
{
int size=0,i=0,j=0;
int a[][];
boolean flag=true;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE SIZE OF MATRIX");
size=sc.nextInt();
a=new int[size][size];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
System.out.print("("+(i+1)+","+(j+1)+"):");
a[i][j]=sc.nextInt();
}
}
System.out.println("MATRIX:");
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
if(i==j)
{
if(a[i][j]!=1)
{
flag=false;
break;
}
}
else if(i!=j)
{
if(a[i][j]!=0)
{
flag=false;
break;
}
}
}
}
if(flag==true)
{
System.out.println("MATRIX IS AN IDENTITY MATRIX");
}
else
{
System.out.println("MATRIX IS NOT AN IDENTITY MATRIX");
}
}
}
Python
import numpy as np
size=int(input("Enter size of Matrix:"))
flag=True
matrix=np.empty([size,size],dtype=np.int)
# Taking input from user
print("Enter elements in matrix:")
for i in range(0,size):
for j in range(0,size):
print("(",(i+1),",",(j+1),")",":",end="")
matrix[i,j]=int(input())
#printing the matrix
print("Matrix:")
for i in range(0, size):
print(matrix[i])
#Checking whether given Matrix is identity matrix or not
for i in range(0,size):
for j in range(0,size):
if(i==j):
if(matrix[i,j]!=1):
flag=False
break
elif(i!=j):
if(matrix[i,j]!=0):
flag=False
break
if(flag==True):
print("Given Matrix is Identity Matrix")
else:
print("Given Matrix is not Identity Matrix")
Coding Store
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale
