Program to display the upper triangular matrix

Explanation

In this program, we need to display the upper triangular matrix.

Upper Triangular Matrix

Upper triangular matrix is a square matrix in which all the elements below the principle diagonal are zero. To find the upper triangular matrix, a matrix needs to be a square matrix that is, the number of rows and columns in the matrix needs to be equal. Dimensions of a typical square matrix can be represented by n x n.

Program to display the upper triangular matrix

Consider the above example, principle diagonal element of given matrix is (1, 6, 6). All the elements below diagonal needs to be zero to convert it into an upper triangular matrix, in our example, those elements are at positions (2,1), (3,1) and (3,2). To convert given matrix into the upper triangular matrix, loop through the matrix and set the values of the element to zero where row number is greater than column number.

Algorithm

  1. Declare and initialize a two-dimensional array a.
  2. Calculate the number of rows and columns present in the array and store it in variables rows and cols respectively.
  3. If the number of rows is not equal to the number of columns, it implies that the given matrix is not a square matrix. Hence, given matrix cannot be converted to the upper triangular matrix. Display the error message.
  4. If rows = cols, traverse the array a using two loops where outer loop represents the rows, and inner loop represents the columns of the array a. To convert given matrix to upper triangular matrix set the elements of the array to 0 where (i > j) that is, the row number is greater than column number.
  5. Display the resulting matrix.

Solution

Python

Output:

Upper triangular matrix: 
1 2 3 
0 6 4 
0 0 6 

C

Output:

Upper triangular matrix: 
1 2 3 
0 6 4 
0 0 6 

JAVA

Output:

Upper triangular matrix: 
1 2 3 
0 6 4 
0 0 6 

C#

Output:

Upper triangular matrix: 
1 2 3 
0 6 4 
0 0 6 

PHP

Output:

Upper triangular matrix: 
1 2 3 
0 6 4 
0 0 6 

Next Topic#




Latest Courses