Answer to Question #188641 in Python for Bhavani

Question #188641

Given a square matrix, print the sum all diagonal elements of the matrix.


1
Expert's answer
2021-05-04T01:53:58-0400
N = int(input())
matrix = []
for i in range(N):
    matrix.append(list(map(int, input().split())))


sumDiagonal1 = sum(matrix[i][i] for i in range(N))
sumDiagonal2 = 0
sumDiagonal1_2 = 0
for i in range(N):
    for j in range(N):
        if i + j == N - 1:
            sumDiagonal2 += matrix[i][j]
if N % 2 == 0:
    sumDiagonal1_2 = sumDiagonal1 + sumDiagonal2
else:
    sumDiagonal1_2 = sumDiagonal1 + sumDiagonal2 - matrix[int((N - 1) / 2)][int((N - 1) / 2)]
print(sumDiagonal1_2)


Output:


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
APPROVED BY CLIENTS