Header Ads

Find difference between sums of two diagonals in matrix

C Program to multiply two matrices
Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along the other diagonal, row index = n – 1 – column index i.e mat[i][j] lies on the second diagonal if i = n-1-j. By using two loops we traverse the entire matrix and calculate the sum across the diagonals of the matrix.
Below is the implementation of this approach:
Program In C:
// C++ program to find the difference
// between the sum of diagonal.
#include <bits/stdc++.h>
#define MAX 100
using namespace std;
int difference(int arr[][MAX], int n)
{
    // Initialize sums of diagonals
    int d1 = 0, d2 = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            // finding sum of primary diagonal
            if (i == j)
                d1 += arr[i][j]
            // finding sum of secondary diagonal
            if (i == n - j - 1)
                d2 += arr[i][j];
        }
    }
    // Absolute difference of the sums
    // across the diagonals
    return abs(d1 - d2);
}
// Driven Program
int main()
{
    int n = 3;
    int arr[][MAX] =
    {
        {11, 2, 4},
        {4 , 5, 6},
        {10, 8, -12}
    };
    cout << difference(arr, n);
    return 0;
}
Output:
15

Program In C++ :
// C++ program to find the difference
// between the sum of diagonal.
#include <bits/stdc++.h>
#define MAX 100
using namespace std;

int difference(int arr[][MAX], int n)
{
    // Initialize sums of diagonals
    int d1 = 0, d2 = 0;

    for (int i = 0; i < n; i++)
    {
        d1 += arr[i][i];
        d2 += arr[i][n-i-1];
    }

    // Absolute difference of the sums
    // across the diagonals
    return abs(d1 - d2);
}

// Driven Program
int main()
{
    int n = 3;

    int arr[][MAX] =
    {
        {11, 2, 4},
        {4 , 5, 6},
        {10, 8, -12}
    };

    cout << difference(arr, n);
    return 0;
}
Output:
15

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Powered by Blogger.