
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find difference between sums of two diagonals in C++.
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
#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
- Related Articles
- JavaScript Program to Find difference between sums of two diagonals
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers
- Computing sums of diagonals of a matrix using Python
- Difference between sums of odd and even digits.
- JavaScript Program to Efficiently compute sums of diagonals of a matrix
- Python Program for Difference between sums of odd and even digits
- C Program for Difference between sums of odd and even digits?
- C Program for the Difference between sums of odd and even digits?
- Possible two sets from first N natural numbers difference of sums as D in C++
- Difference between sums of odd level and even level nodes of a Binary Tree in Java
- Difference between sums of odd position and even position nodes of a Binary Tree in Java
- Find minimum difference between any two element in C++
- Find the compatibility difference between two arrays in C++
- Program to find maximum sum of two sets where sums are equal in C++
- Find the minimum difference between Shifted tables of two numbers in Python

Advertisements