Matrix Diagonal Sum
Given a square matrix, print the sum all diagonal elements of the matrix.
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.
The output should be a single integer denoting the sum of all the diagonal elements.
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
def print_diag_sum(matrix, n):
'''
function print the sum all diagonal elements of the square matrix
with N rows
'''
s = 0
print(matrix)
for i in range(n):
if i == n - i - 1:
s += matrix[i][i]
else:
s += matrix[i][i] + matrix[i][n-i-1]
print(s)
while True:
try:
N = int(input('enter dimension of a square matrix or 0 to exit '))
if N == 0:
break
except ValueError:
print('incorrect input')
continue
matrix = []
k = N
while k > 0:
try:
line = list(map(int, input().split()))
except ValueError:
print('ValueError')
continue
if len(line) == N:
matrix.append(line)
k -= 1
else:
print('incorect input')
continue
print_diag_sum(matrix, N)
Comments
Leave a comment