Answer to Question #217923 in Python for srikanth

Question #217923
Matrix Diagonal Sum

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

Input

The first line of input will be an integer N, denoting the no. of rows in the matrix. The following N lines will contain space-separated integers denoting the elements of each row of the matrix.

Output

The output should be a single integer denoting the sum of all the diagonal elements.

Explanation

For example, if the given N is 3, and the given matrix is
1 2 3
4 5 6
7 8 9
The diagonal and anti-diagonal elements of the above matrix are 1, 3, 5, 7, 9. So the output should be 25

Sample Input 
3
1 2 3
4 5 6
7 8 9
Sample Output 
25


1
Expert's answer
2021-07-17T10:41:41-0400
N = int(input()) # Ask the user for a value of N
mat = [] # Create an empty matrix
main_diagonal =int(0) # Variable to store the sum of main diagonal
anti_diagonal = int(0) # Variable to store the sum of anti diagonal
total_sum = int(0)
for i in range(N):  # Enter the row elements
    mat.append(list(map(int, input().split())))
for i in range(N):
    main_diagonal = main_diagonal + mat[i][i] # Sum the main diagonal

i = N-1
j = 0
while i >= 0:
    if i != j:
        anti_diagonal = anti_diagonal + mat[i][j] # Sum the anti diagonal
    i = i - 1
    j = j + 1

total_sum = main_diagonal + anti_diagonal # calculate the total sum
print(total_sum)  # Display the total sum

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
New on Blog
APPROVED BY CLIENTS