Identity Matrix

Identity Matrix


Write a program to check if an entered matrix is identity matrix. An identity matrix is one which has only 1s in its principal diagonal and 0s everywhere else.

import java.io.*; class IdentityMatrix { public static void main(String ar[])throws Exception { BufferedReader ob=new BufferedReader( new InputStreamReader(System.in)); int i,j,n; boolean flag; System.out.println("Enter the no of rows for a square matrix : "); n=Integer.parseInt(ob.readLine()); int a[][]=new int[n][n]; System.out.println("\nEnter "+(n*n)+" elements : "); for(i=0;i< n;i++) { for(j=0;j< n;j++) { a[i][j]=Integer.parseInt(ob.readLine()); } } flag=false; for(i=0;i< n;i++) { for(j=0;j< n;j++) { if(i==j && a[i][j]!=1) flag=true; if(i!=j && a[i][j]!=0) flag=true; } } if(flag) System.out.println("\nNot an identity matrix."); else System.out.println("\nIt is an identity matrix."); } }

Have something to say? Log in to comment on this post.

0 comments