Part of the series

Several example codes

~2 min read • Updated Oct 13, 2025

Program Overview

This Python program reads an n × n square matrix and calculates the sum of elements on both the main and secondary diagonals.
- Main diagonal: positions where i == j
- Secondary diagonal: positions where i + j == n - 1


Python Code:


def read_matrix(n: int) -> list[list[int]]:
    print(f"Enter elements for a {n}×{n} matrix:")
    matrix = []
    for i in range(n):
        row = list(map(int, input(f"Row {i+1}: ").strip().split()))
        if len(row) != n:
            print("Each row must contain exactly n elements.")
            exit()
        matrix.append(row)
    return matrix

def sum_diagonals(matrix: list[list[int]]) -> int:
    n = len(matrix)
    total = 0
    for i in range(n):
        total += matrix[i][i]  # Main diagonal
        if i != n - 1 - i:     # Avoid double-counting center element
            total += matrix[i][n - 1 - i]  # Secondary diagonal
    return total

# Read matrix size
n = int(input("Enter matrix size (n): "))
if n < 1:
    print("Matrix size must be positive.")
    exit()

# Read and compute
mat = read_matrix(n)
result = sum_diagonals(mat)
print(f"\nSum of main and secondary diagonals: {result}")

Sample Output:


Input:  
1 2 3  
4 5 6  
7 8 9  

Main diagonal: 1 + 5 + 9 = 15  
Secondary diagonal: 3 + 5 + 7 = 15  
Final sum: 15 + 15 - 5 = 25 (since 5 appears in both diagonals)

Output:  
Sum of main and secondary diagonals: 25

Written & researched by Dr. Shahin Siami