Answer to Question #181189 in C++ for luna

Question #181189

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-17T07:10:57-0400
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>

using namespace std;

int A[100][100];

int main() {
    
  string TString;
  int N;

  getline(cin, TString);
  N = stoi(TString);

  if(N < 1 || N > 100) {
    exit(1);
  }

  for(int i = 0; i< N;i++) {
    string line;
    getline(cin, line);    
    stringstream LineStream(line);
    
    for(int j=0;j<N;j++){
        LineStream >> A[i][j];
    }
  }
    int d1 =0;
    int d2 =0;
    
    for(int i=0;i<N;i++) {
        d1 += A[i][i];
        d2 += A[i][N-i-1];
    }
    
    cout << abs(d1-d2) << 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