C++ Program to Find Sum of Diagonal Elements
sum += matrix[i][i]; inside a for loop iterating over the matrix size.Examples
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the example matrix {{5, 1, 0}, {2, 7, 3}, {4, 6, 9}} through the code.
Initialize sum and size
sum = 0, size = 3
First iteration (i=0)
sum = 0 + matrix[0][0] = 0 + 5 = 5
Second iteration (i=1)
sum = 5 + matrix[1][1] = 5 + 7 = 12
Third iteration (i=2)
sum = 12 + matrix[2][2] = 12 + 9 = 21
End loop and print sum
Output: Sum of diagonal elements: 21
| Iteration | i | matrix[i][i] | sum |
|---|---|---|---|
| 1 | 0 | 5 | 5 |
| 2 | 1 | 7 | 12 |
| 3 | 2 | 9 | 21 |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop with array | O(n) | O(1) | Fixed-size matrices, simplicity |
| Function abstraction | O(n) | O(1) | Code reuse and clarity |
| Vector of vectors | O(n) | O(1) | Dynamic size matrices |