JavaScript: Check whether a given matrix is lower triangular or not
JavaScript Basic: Exercise-121 with Solution
Write a JavaScript program to check whether a given matrix is lower triangular or not.
Note: A square matrix is called lower triangular if all the entries above the main diagonal are zero.
Sample Solution:
JavaScript Code:
// Function to check if a matrix is a lower triangular matrix
function lower_triangular_matrix(user_matrix) {
for (var i = 0; i < user_matrix.length; i++) {
for (var j = 0; j < user_matrix[0].length; j++) {
// If element is above the main diagonal and not equal to zero, return false
if (j > i && user_matrix[i][j] !== 0) {
return false;
}
}
}
return true; // Matrix is lower triangular
}
// Test cases
console.log(lower_triangular_matrix([[1, 0, 0],[2, 0, 0], [0, 3, 3]])); // Output: true (Lower triangular matrix)
console.log(lower_triangular_matrix([[1, 0, 1],[2, 0, 0], [0, 3, 3]])); // Output: false (Not a lower triangular matrix)
Output:
true false
Live Demo:
See the Pen javascript-basic-exercise-121 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Function to check if a matrix is a lower triangular matrix
const lower_triangular_matrix = (user_matrix) => {
for (let i = 0; i < user_matrix.length; i++) {
for (let j = 0; j < user_matrix[0].length; j++) {
// If element is above the main diagonal and not equal to zero, return false
if (j > i && user_matrix[i][j] !== 0) {
return false;
}
}
}
return true; // Matrix is lower triangular
};
// Test cases
console.log(lower_triangular_matrix([[1, 0, 0],[2, 0, 0], [0, 3, 3]])); // Output: true (Lower triangular matrix)
console.log(lower_triangular_matrix([[1, 0, 1],[2, 0, 0], [0, 3, 3]])); // Output: false (Not a lower triangular matrix)
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to check whether a point lies strictly inside a given circle.
Next: JavaScript program to check whether a given array of integers represents either a strictly increasing or a strictly decreasing sequence.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-basic-exercise-121.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics