Given a square matrix, calculate the absolute difference between the sums of its diagonals. For example, the square matrix m is shown below:
1 2 3
4 5 6
7 8 9
The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 7 =15. Their absolute difference is |15 – 15| = 0
Sample Input
3
11 2 4
4 5 6
10 8 12
Sample output
17
Note: The number 3 on the first line of input represent the dimension of the square matrix. In this case, it’s a 3 x 3 two-dimensional array.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int N; // matrix N x N
cin >> N;
vector<vector<int>> matrix(N, vector<int>(N)); // Create matrix
// Fill matrix
for(int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> matrix[i][j];
}
}
// Variables for sums
int sum_left_to_right = 0;
int sum_right_to_left = 0;
// Calculate diagonal elements sums
for(int i = 0; i < N; i++) {
sum_left_to_right += matrix[i][i];
sum_right_to_left += matrix[i][N-1-i];
}
// Calculate absolute difference and print it
cout << abs(sum_left_to_right - sum_right_to_left) << endl;
return 0;
}
Comments
Leave a comment