Python program to calculate the sum of upper and lower triangle in a matrix

In this article, we will learn to calculate the sum of the upper and lower triangle (including the diagonal) in a matrix using Python. A triangle is typically divided into two parts lower and upper triangles. A triangle with all elements below the main diagonal is called a lower triangle. A triangle with all elements above the main diagonal is called an upper triangle.


Input: mat = [[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]]
Sum of the lower triangle is: 34
Sum of the upper triangle is: 26

Sum of Upper and Lower Triangle

1. Load the matrix.

2. Declare two variables lower_sum and upper_sum to store the sum of the lower and upper triangles respectively.

3. Iterate through range (0, r) as an outer loop.

4. Iterate through range (0, c) as an inner loop.

5. Now, check the current element belonging to the lower triangle if true add the element to lower_sum.

6. Else, add the element to upper_sum.

7. Finally, return the upper_sum and lower_sum.

def sum_of_lower_upper(mat):
    r = len(mat)
    c = len(mat[0])
    lower_sum = 0
    upper_sum = 0
    for i in range(r):
        for j in range(c):
            if (i<=j):
                upper_sum += mat[i][j]
    print("Sum of the upper triangle: ", upper_sum)

    for i in range(r):
        for j in range(c):
            if (j<=i):
                lower_sum += mat[i][j]
    print("Sum of the lower triangle: ", lower_sum)

mat = [[10, 21, 3], [24, 51, 6], [7, 8, 9]]
for i in range(len(mat)):
    for j in range(len(mat[0])):
        print(mat[i][j], end=" ")


10 21 3 
24 51 6 
7 8 9
Sum of the upper triangle: 100
Sum of the lower triangle: 109

Also, refer

Leave a Reply

Your email address will not be published. Required fields are marked *