0
0
CppProgramBeginner · 2 min read

C++ Program to Find Sum of Diagonal Elements

To find the sum of diagonal elements in C++, use a loop to add elements where the row and column indices are equal, like sum += matrix[i][i]; inside a for loop iterating over the matrix size.
📋

Examples

Inputmatrix = {{1, 2}, {3, 4}}
OutputSum of diagonal elements: 5
Inputmatrix = {{5, 1, 0}, {2, 7, 3}, {4, 6, 9}}
OutputSum of diagonal elements: 21
Inputmatrix = {{10}}
OutputSum of diagonal elements: 10
🧠

How to Think About It

To find the sum of diagonal elements, think of a square matrix as a grid with rows and columns. The diagonal elements are those where the row number and column number are the same. So, you just add up all elements where the row index equals the column index.
📐

Algorithm

1
Get the size of the square matrix.
2
Initialize a variable sum to zero.
3
Loop through the matrix indices from 0 to size-1.
4
Add the element at position [i][i] to sum.
5
After the loop ends, return or print the sum.
💻

Code

cpp
#include <iostream>
using namespace std;

int main() {
    int matrix[3][3] = {{5, 1, 0}, {2, 7, 3}, {4, 6, 9}};
    int sum = 0;
    int size = 3;
    for (int i = 0; i < size; i++) {
        sum += matrix[i][i];
    }
    cout << "Sum of diagonal elements: " << sum << endl;
    return 0;
}
Output
Sum of diagonal elements: 21
🔍

Dry Run

Let's trace the example matrix {{5, 1, 0}, {2, 7, 3}, {4, 6, 9}} through the code.

1

Initialize sum and size

sum = 0, size = 3

2

First iteration (i=0)

sum = 0 + matrix[0][0] = 0 + 5 = 5

3

Second iteration (i=1)

sum = 5 + matrix[1][1] = 5 + 7 = 12

4

Third iteration (i=2)

sum = 12 + matrix[2][2] = 12 + 9 = 21

5

End loop and print sum

Output: Sum of diagonal elements: 21

Iterationimatrix[i][i]sum
1055
21712
32921
💡

Why This Works

Step 1: Identify diagonal elements

Diagonal elements have the same row and column index, so we use matrix[i][i] to access them.

Step 2: Sum elements in a loop

Looping from 0 to size-1 lets us add each diagonal element to the sum one by one.

Step 3: Print the result

After adding all diagonal elements, printing the sum shows the final answer.

🔄

Alternative Approaches

Using a function to sum diagonal elements
cpp
#include <iostream>
using namespace std;

int sumDiagonal(int matrix[][3], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += matrix[i][i];
    }
    return sum;
}

int main() {
    int matrix[3][3] = {{5,1,0},{2,7,3},{4,6,9}};
    cout << "Sum of diagonal elements: " << sumDiagonal(matrix, 3) << endl;
    return 0;
}
This approach improves code reuse by separating logic into a function.
Using a vector of vectors for dynamic size
cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int>> matrix = {{5,1,0},{2,7,3},{4,6,9}};
    int sum = 0;
    for (int i = 0; i < matrix.size(); i++) {
        sum += matrix[i][i];
    }
    cout << "Sum of diagonal elements: " << sum << endl;
    return 0;
}
Using vectors allows flexible matrix size but requires including <vector>.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops once through the matrix diagonal elements, so it runs in linear time relative to the matrix size.

Space Complexity

Only a few variables are used for sum and loop counters, so space usage is constant.

Which Approach is Fastest?

All approaches run in O(n) time; using arrays or vectors mainly affects flexibility, not speed.

ApproachTimeSpaceBest For
Simple loop with arrayO(n)O(1)Fixed-size matrices, simplicity
Function abstractionO(n)O(1)Code reuse and clarity
Vector of vectorsO(n)O(1)Dynamic size matrices
💡
Always ensure the matrix is square before summing diagonal elements to avoid errors.
⚠️
Beginners often forget that diagonal elements have equal row and column indices and sum all elements instead.