# Java Program to determine whether a given matrix is an identity matrix

In this program, we need to check whether the given matrix is an identity matrix.

Identity Matrix

A matrix is said to be an identity matrix if it is a square matrix in which elements of principle diagonal are ones, and the rest of the elements are zeroes.

### Algorithm

• STEP 1: START
• STEP 2: DEFINE rows, cols
• STEP 3: SET flag =true
• STEP 4: INITIALIZE matrix a[][] ={{1,0,0},{0,1,0}, {0,0,1}}
• STEP 5: rows = a.length
• STEP 6: cols = a.length
• STEP 7: if(rows!=cols)
then
PRINT “Matrix should be a square matrix”
else
go to step 8
• STEP 8: REPEAT STEP 9 to STEP 11 UNTIL i<rows
//for(i=0; i<rows; i++)
• STEP 9: REPEAT STEP 10 to STEP 11 UNTIL j<cols
//for(j=0; j<cols; j++)
• STEP 10: if(i==j && a[i][j]== 1) then
SET flag =false
break
• STEP 11: if( i!=j && a[i][j]!=0)
SET flag = false
break
• STEP 12: if(flag)
then PRINT (“Given matrix is an identity matrix”)
else
PRINT (“Given matrix is not an identity matrix”)
• STEP 13: END

### Program:

1. public class IdentityMatrix
2. {
3.     public static void main(String[] args) {
4.         int rows, cols;
5.         boolean flag = true;
6.
7.         //Initialize matrix a
8.         int a[][] = {
9.                         {1, 0, 0},
10.                         {0, 1, 0},
11.                         {0, 0, 1}
12.                     };
13.
14.         //Calculates the number of rows and columns present in the given matrix
15.
16.           rows = a.length;
17.         cols = a.length;
18.
19.         //Checks whether given matrix is a square matrix or not
20.         if(rows != cols){
21.             System.out.println(“Matrix should be a square matrix”);
22.         }
23.         else {
24.             //Checks if diagonal elements are equal to 1 and rest of elements are 0
25.             for(int i = 0; i < rows; i++){
26.                 for(int j = 0; j < cols; j++){
27.                   if(i == j && a[i][j] != 1){
28.                       flag = false;
29.                       break;
30.                   }
31.                   if(i != j && a[i][j] != 0){
32.                       flag = false;
33.                       break;
34.                   }
35.                 }
36.             }
37.
38.             if(flag)
39.                 System.out.println(“Given matrix is an identity matrix”);
40.             else
41.                 System.out.println(“Given matrix is not an identity matrix”);
42.         }
43.     }
44. }

Output:

`Given matrix is an identity matrix`