File tree Expand file tree Collapse file tree 1 file changed +115
-0
lines changed
InterviewPrograms/src/com/java/matrix Expand file tree Collapse file tree 1 file changed +115
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .java .matrix ;
2+
3+ /*
4+ * Identity Matrix
5+ *
6+ * If a matrix is a Identity matrix then it should
7+ * follow all the conditions
8+ * 1. It should be square matrix row == column
9+ * 2. All the elements of main diagonal should be 1
10+ * 3. Rest of the elements should be 0.
11+ *
12+ * If any of the above conditions are not satisfied
13+ * then the matrix is not Identity Matrix.
14+ *
15+ * Examples of Identity matrix
16+ * 1 0 0
17+ * 0 1 0
18+ * 0 0 1
19+ *
20+ * 1 0 0 0
21+ * 0 1 0 0
22+ * 0 0 1 0
23+ * 0 0 0 1
24+ *
25+ * NOT Identity matrix
26+ * 1 2
27+ * 3 4
28+ *
29+ * 1 1 1
30+ * 1 0 1
31+ * 1 1 1
32+ *
33+ * 1 0 0
34+ * 0 1 0
35+ *
36+ */
37+ public class IdentityMatrix {
38+ public static void main (String [] args ) {
39+ int matrix [][] = {
40+ {1 ,0 ,0 ,0 },
41+ {0 ,1 ,0 ,0 },
42+ {0 ,0 ,1 ,0 },
43+ {0 ,0 ,0 ,1 }
44+ };
45+ /* int matrix[][] = {
46+ {1,0,0},
47+ {0,1,0},
48+ {0,0,1}
49+ };*/
50+ int row = 4 ;
51+ int col = 4 ;
52+
53+ //row and col should be same to make square matrix
54+ if (row != col ){
55+ System .out .println ("Given matrix is NOT a Identity Matrix" );
56+ return ;
57+ }
58+
59+ //main diagonal elements should be 1
60+ for (int i =0 ;i <row ;i ++)
61+ if (matrix [i ][i ] != 1 ){
62+ System .out .println ("Given matrix is NOT a Identity Matrix" );
63+ return ;
64+ }
65+
66+ //rest of the elements should be 0
67+ for (int i =0 ;i <row ;i ++)
68+ for (int j =0 ;j <col ;j ++)
69+ if (i != j && matrix [i ][j ] != 0 ){
70+ System .out .println ("Given matrix is NOT a Identity Matrix" );
71+ return ;
72+ }
73+ //if all the 3 conditions are satisfied
74+ //Given matrix is Identity Matrix
75+
76+ System .out .println ("Given matrix is a Identity Matrix" );
77+ }
78+ }
79+ /*
80+ INPUT
81+ matrix[][] = {
82+ {1,0,0,0},
83+ {0,1,0,0},
84+ {0,0,1,0},
85+ {0,0,0,1}
86+ };
87+ OUTPUT
88+ Given matrix is a Identity Matrix
89+
90+ INPUT
91+ matrix[][] = {
92+ {1,0,0},
93+ {0,1,0},
94+ {0,0,1},
95+ };
96+ OUTPUT
97+ Given matrix is a Identity Matrix
98+
99+ INPUT
100+ matrix[][] = {
101+ {1,1,1},
102+ {0,1,1},
103+ {1,0,1},
104+ };
105+ OUTPUT
106+ Given matrix is NOT a Identity Matrix
107+
108+ INPUT
109+ matrix[][] = {
110+ {1,0,0},
111+ {0,1,0}
112+ };
113+ OUTPUT
114+ Given matrix is NOT a Identity Matrix
115+ */
You can’t perform that action at this time.
0 commit comments