Question #188839

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


Expert's answer

def ReadMatrix(N):
    matrix = []
    for i in range(N):
        row = [int(j) for j in input().split()]
        matrix.append(row) 
    return matrix

N = int(input())
matrix = ReadMatrix(N)

diagonal = 0
for i in range(N):
    diagonal += matrix[i][i]

antidiagonal = 0
for i in range(N):
    antidiagonal += matrix[i][N - 1 - i]

if N % 2 != 0:
    antidiagonal -= matrix[N // 2][N // 2]

print(diagonal + antidiagonal)
LATEST TUTORIALS
APPROVED BY CLIENTS