given a square matrix print the sum all diagonal elements of the matrix
sample input :
3
1 2 3
4 5 6
7 8 9
sample output:
25
N = int(input())
matrix = []
for i in range(N):
matrix.append([int(j) for j in input().split()])
diagonalSum = 0
antiDiagonalSum = 0
for i in range(N):
diagonalSum += matrix[i][i]
antiDiagonalSum += matrix[i][N - 1 - i]
if N % 2 != 0:
antiDiagonalSum -= matrix[N // 2][N // 2]
print(diagonalSum + antiDiagonalSum)
Comments
Leave a comment