# Find difference between sums of two diagonals in C++.

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Here we will see how to get the difference between the sums of two diagonals of a given matrix. Suppose we have a matrix of order N x N, we have to get the sum of primary and secondary diagonals, then get the difference of them. To get the major diagonal, we know that the row index and column index increases simultaneously. For the second diagonal, row index and column index values are increased by this formula row_index = n – 1 – col_index. After getting the sum, take the difference and return a result.

## Example

Live Demo

#include<iostream>
#include<cmath>
#define MAX 100
using namespace std;
int diagonalSumDifference(int matrix[][MAX], int n) {
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++) {
sum1 += matrix[i][i];
sum2 += matrix[i][n-i-1];
}
return abs(sum1 - sum2);
}
// Driven Program
int main() {
int n = 3;
int matrix[][MAX] = {
{11, 2, 4},
{4 , 5, 6},
{10, 8, -12}
};
cout << "Difference of the sum of two diagonals: " << diagonalSumDifference(matrix, n);
}

## Output

Difference of the sum of two diagonals: 15