Javascript Program to check if matrix is upper triangular
Last Updated :
12 Sep, 2024
Improve
Given a square matrix and the task is to check the matrix is in upper triangular form or not. A square matrix is called upper triangular if all the entries below the main diagonal are zero.
Examples:
Input : mat[4][4] = {{1, 3, 5, 3},
{0, 4, 6, 2},
{0, 0, 2, 5},
{0, 0, 0, 6}};
Output : Matrix is in Upper Triangular form.
Input : mat[4][4] = {{5, 6, 3, 6},
{0, 4, 6, 6},
{1, 0, 8, 5},
{0, 1, 0, 6}};
Output : Matrix is not in Upper Triangular form.
// Java script Program to check upper
// triangular matrix.
let N = 4;
// Function to check matrix is in
// upper triangular form or not.
function isUpperTriangularMatrix(mat) {
for (let i = 1; i < N; i++)
for (let j = 0; j < i; j++)
if (mat[i][j] != 0)
return false;
return true;
}
// driver function
let mat = [[1, 3, 5, 3],
[0, 4, 6, 2],
[0, 0, 2, 5],
[0, 0, 0, 6]];
if (isUpperTriangularMatrix(mat))
console.log("Yes");
else
console.log("No");
// contributed by sravan kumar
27
1
// Java script Program to check upper
2
// triangular matrix.
3
let N = 4;
4
5
// Function to check matrix is in
6
// upper triangular form or not.
7
function isUpperTriangularMatrix(mat) {
8
for (let i = 1; i < N; i++)
9
for (let j = 0; j < i; j++)
10
if (mat[i][j] != 0)
11
return false;
12
return true;
13
}
14
15
// driver function
16
17
let mat = [[1, 3, 5, 3],
18
[0, 4, 6, 2],
19
[0, 0, 2, 5],
20
[0, 0, 0, 6]];
21
22
if (isUpperTriangularMatrix(mat))
23
console.log("Yes");
24
else
25
console.log("No");
26
27
// contributed by sravan kumar
Output
Yes
Complexity Analysis:
- Time Complexity: O(n2), where n represents the number of rows and columns of the matrix.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Program to check if matrix is upper triangular for more details!