Answer to Question #182330 in C++ for Luna

Question #182330

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.



1
Expert's answer
2021-04-16T15:53:25-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS