Matrix Diagonal Sum in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

int diagSum(int a[10][10], int n) {
    int s = 0;
    for (int i = 0; i < n; i++)
        s += a[i][i];
    return s;
}

C Output

Input:  
1 2 3  
4 5 6  
7 8 9  

Output:  
Main Diagonal Sum: 15  // 1 + 5 + 9


C++ Program

int diagSum(vector<vector<int>> &a) {
    int s = 0;
    for (int i = 0; i < a.size(); i++)
        s += a[i][i];
    return s;
}

C++ Output

Input:  
{1, 0, 0},  
{0, 5, 0},  
{0, 0, 9}

Output:  
Main Diagonal Sum: 15


JAVA Program

int diagSum(int[][] a) {
    int s = 0;
    for (int i = 0; i < a.length; i++)
        s += a[i][i];
    return s;
}

JAVA Output

Input:  
{{2, 3}, {4, 5}}

Output:  
Main Diagonal Sum: 7


Python Program

def diag_sum(a):
    print("Main Diagonal Sum:", sum(a[i][i] for i in range(len(a))))

Python Output

Input:  
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output:  
Main Diagonal Sum: 15


In-depth Explanation
Example
For a 3x3 matrix such as:

1 2 3  /
4 5 6  /
7 8 9
The main diagonal is the sum of: 1, 5, and 9. Sum equals 1 + 5 + 9 = 15.
If you're asked for the secondary diagonal (which goes right to left), it is 3 + 5 + 7 = 15 also .
.
In most introductory programs, we focus on the main diagonal, where row index equals column index.
Real-Life Analogy
Imagine you’re organizing data in a grid — like seating numbers in a theater, or days in a calendar table. The diagonal represents a consistent path across — like one leader from each team lined up diagonally in a group photo. Their combined total (say, leadership scores) might represent a pattern across categories — that's your diagonal sum.

Why It Matters
Diagonal sums show up in:

Matrix identity tests (identity matrix contains 1s along the diagonal only)

Spiral and zigzag patterns

Sudoku and grid games

Image processing, wherein pixels exist in a diagonal pattern

It also establishes basics of:

Working with 2D arrays

Looping with regular index pairs (such as i == j)

Unpacking special data from structured formats

This exercise assists novice developers in forming intuition about accessing and manipulating matrix parts.

What You Learn from This
Traversal of 2D arrays through index logic

Understanding properties of symmetric matrices

How patterns such as diagonals are recognized through index relationships

Space and time optimization through employing one loop for diagonals

You also consolidate your fundamentals in for-loops, matrix organization, and summation of values.

Interview Relevance and Actual Projects
This sort of problem is typically asked in:

Coding bootcamps and initial technical rounds

Pattern detection issues

Logical reasoning tests with 2D arrays

In actual development, it's helpful in:

Spreadsheet processors (such as Excel formula validations)

Graphical data organizations

Chessboard/game grids with diagonal movement

Linear algebra operations (e.g., matrix trace)

You may also be required to:

Compute both diagonals

Skip the center element if it overlaps for odd-sized matrices

Generalize to non-square matrices (where transpose or identity verification is not applicable)

SEO-Optimized Explanation
Matrix diagonal sum in C, C++, Java, and Python is a basic problem that leads newcomers to handling two-dimensional arrays. By adding up the elements in which row and column indices are the same, you get the main diagonal, commonly employed in mathematical modeling, grids of data, and game development. The idea is crucial to grasp when it comes to accessing matrix elements in an efficient manner and is the foundation for further operations such as transposition of a matrix, trace, and identity matrix verification. Be it for a coding interview or actual programming task, the practice of matrix diagonal operations enhances reasoning, indexing proficiency, and 2D array operation confidence.