Answer to Question #238169 in Python for C N Manjula

Question #238169
You are given a square matrix of size NxN, write a program to print the sum of upper and lower triangular elements.
Upper triangle consists of elements on the anti-diagonal and above it. The lower triangle consists of elements on the anti-diagonal and below it.

Explanation:
In the example,if the given matrix is

1 2 3
4 5 6
7 8 9

The upper triangle consists of elements on the anti-diagonal and above on it.

1 2 3
4 5
7

The sum of upper triangle elements is (1+2+3+4+5+7) equal to 22.
The lower triangle consists of elements on the anti-diagonal and below to it.

3
5 6
7 8 9

The sum of lower triangle elements is (3+5+6+7+8+9) equal to 38.

So the output should be

22
38
1
Expert's answer
2021-09-17T13:09:30-0400
def calculateSum(matrix, r, c):
    upperSum = 0
    lowerSum = 0
    for i in range(r):
        for j in range(c-1,0,-1):
            if (i >= j):
                upperSum += matrix[i][j]
 
    print(upperSum);
    counter=0
    # to calculate sum of lower
    for i in range(r-1,-1,-1):
        for j in range(counter,c):
            lowerSum += matrix[i][j]
        counter+=1
    print(lowerSum)
 


R = int(input())
C = int(input()) 
matrix = []
for i in range(R):
    arr = [int(i) for i in input().split()]
    matrix.append(arr)
    
calculateSum(matrix, R, C)
 




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS