Dsa
Matrix
Easy
Diagonal Sum of a Square Matrix
You are given a square matrix of integers. Write a program to calculate the sum of the diagonal elements. The main diagonal runs from the top-left to the bottom-right corner of the matrix.
Input Format:
The first line contains an integer n (1 <= n <= 100), the size of the matrix.
Each of the next n lines contains n space-separated integers representing the elements of the matrix.
Output Format:
Print a single integer, the sum of the diagonal elements.
Example:
Input:
3
1 2 3
4 5 6
7 8 9
Output:
15
Key concepts
matrixsumdiagonal
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now