Open In App

PHP Program to Check for Upper Triangular Matrix

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Square Matrix, the task is to check whether the matrix is in upper triangular form or not. A square matrix is called upper triangular matrix if all the entries below the main diagonal are zero.
 

Examples:  

Input: mat = [
[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 = [
[5, 6, 3, 6],
[0, 4, 6, 6],
[1, 0, 8, 5],
[0, 1, 0, 6]
];
Output: Matrix is not in Upper Triangular form

Here is the complete PHP program to check if the matrix is in upper triangular form:

PHP
<?php
// PHP Program to check for 
// upper triangular matrix

$N = 4;

// Function to check matrix is in 
// upper triangular form or not
function isUpperTriangularMatrix($mat) {
    global $N;
    for ($i = 1; $i < $N; $i++) {
        for ($j = 0; $j < $i; $j++) {
            if ($mat[$i][$j] != 0) {
                return false;
            }
        };
    }
    return true;
}

// Driver Code
$mat = [
  	[1, 3, 5, 3], 
  	[0, 4, 6, 2], 
  	[0, 0, 2, 5], 
  	[0, 0, 0, 6]
];

if (isUpperTriangularMatrix($mat)) {
    echo "Yes";
} else {
    echo "No";
}

?>

Output
Yes

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!



Next Article
Practice Tags :

Similar Reads