forked from fineanmol/Hacktoberfest2026
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdentityMatrix.java
More file actions
49 lines (45 loc) · 1.37 KB
/
IdentityMatrix.java
File metadata and controls
49 lines (45 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//Java program to check for
//identity matrix
public class IdentityMatrix
{
public static void main(String[] args) {
int rows, columns;
boolean flag = true;
//Initialize matrix a
int arr[][] = {
{1, 2, 1},
{0, 1, 0},
{1, 0, 1}
};
//Find out the
//number of rows and columns
//in the given matrix
rows = arr.length;
columns = arr[0].length;
//Checks whether square matrix or not
if(rows != columns){
System.out.println("Enter a square matrix");
}
// For an identity matrix
//Diagonal elements must equal 1
//Others should equal 0
else {
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
if(i == j && arr[i][j] != 1){
flag = false;
break;
}
if(i != j && arr[i][j] != 0){
flag = false;
break;
}
}
}
if(flag)
System.out.println("Given matrix is an identity matrix");
else
System.out.println("Given matrix is not an identity matrix");
}
}
}