# Display the upper triangular matrix in Python

In this tutorial, we will study the process of the upper triangular matrix in python3. Let’s understand what the upper triangular matrix means, it means all the values above the principal diagonal (including the principal diagonal). Similarly, there is something called the lower triangular matrix which involves the values below the principal diagonal (including the principal diagonal). This can easily be understood with the help of the given figure. Then we will learn how to print or display the upper triangular matrix in Python.

Now let’s begin with how to display the upper triangular matrix in Python.

This is only possible in the case of a square matrix. In the figure, if we closely see the non=zero values represent a right-angled triangle at the upper end.

But today we are only concerned about the upper triangular matrix and its code in Python.

Steps/Algorithm involved for displaying the upper triangular matrix in python3

- Compare the row index and column index.
- If row index is less than or equal to column index print the value at that position.
- If not then print 0.

Trying writing the code by yourself before looking at the code below. Happy coding coders.

### Program to Display upper triangular matrix in Python

n,m=map(int,input("Enter the size of matrix: ").split(" ")) print("Enter elements") arr=[] for i in range(n): val=[] for j in range(m): val.append(int(input())) arr.append(val) print("The upper triangular matrix is as follows: ") for i in range(n): for j in range(m): if(i<=j): print(arr[i][j],end="\t") else: print(0,end="\t") print()

#### Ouput:

Enter the size of matrix: 4 4 Enter elements 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19 The upper triangular matrix is as follows: 1 2 3 4 0 7 8 9 0 0 13 14 0 0 0 19

Hence you can similarly try to write the code for a lower triangular matrix. The only difference is the condition gets reversed.

Also read:

## Leave a Reply

You must be logged in to post a comment.