Practice › Arrays
Matrix Diagonal Sum
Easy · Arrays · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
For an n × n matrix, print the sum of the elements on the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). When n is odd, the centre element lies on both — count it only once.
Input
First line: n. Next n lines: n integers each.
Output
The diagonal sum.
Constraints
- 1 ≤ n ≤ 500
- −10^6 ≤ a[i][j] ≤ 10^6
Example 1
Input
3 1 2 3 4 5 6 7 8 9
Output
25
Example 2
Input
2 1 1 1 1
Output
4
Hints
- The primary diagonal is a[i][i]; the secondary diagonal is a[i][n − 1 − i].
- They meet only when i = n − 1 − i, i.e. the centre of an odd-sized matrix.
Approach
One loop over i adds a[i][i] and a[i][n − 1 − i], skipping the second term when both indices point at the same cell. Use a 64-bit sum to be safe.
Complexity: O(n) time after reading the matrix · O(n²) space for the input
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<long long>> a(n, vector<long long>(n));
for (auto &row : a)
for (auto &x : row) cin >> x;
long long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i][i];
if (i != n - 1 - i) sum += a[i][n - 1 - i];
}
cout << sum << "\n";
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
a = [list(map(int, data[1 + i * n : 1 + (i + 1) * n])) for i in range(n)]
total = 0
for i in range(n):
total += a[i][i]
if i != n - 1 - i:
total += a[i][n - 1 - i]
print(total)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[][] a = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
in.nextToken();
a[i][j] = (long) in.nval;
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i][i];
if (i != n - 1 - i) sum += a[i][n - 1 - i];
}
System.out.println(sum);
}
}