Diagonal Difference C++ Program
Diagonal difference C++ program.
In this article, you will learn how to make a diagonal difference C++ program.
Example
Enter the size of the array::
4
Enter the elements of the array in [4 x 4] matrix form::
10 8 -12 2
4 5 90 3
11 2 4 6
4 5 6 7
Diagonal Difference = 72
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
while
loop - C++
for
loop
Source Code
// Diagonal Difference C++ Program
#include <iostream>
using namespace std;
int main() {
int s = 0;
cout << "Enter the size of the array::\n";
cin >> s;
int arr[s][s];
cout << "\nEnter the elements of the array in [" << s << " x " << s << "] matrix form::\n";
int i=0;
while (i<s) {
int j=0;
while (j<s) {
cin >> arr[i][j];
j++;
}
i++;
}
// It will calculate the diagonal difference
int df = 0, s2=s-1, d1=0, d2=0;
i=0;
while (i<s) {
d1 += arr[i][i];
d2 += arr[i][s2];
s2--;
i++;
}
df = d1 > d2 ? d1 - d2 : d2 - d1;
// It will return the final output
cout << "\nDiagonal Difference = " << df << "\n";
return 0;
}
Output
Enter the size of the array::
4
Enter the elements of the array in [4 x 4] matrix form::
10 8 -12 2
4 5 90 3
11 2 4 6
4 5 6 7
Diagonal Difference = 72
Explanation
In this given program we have taken the size of array 4 and the elements of the array in [4 x 4]
matrix form following: 10 8 -12 2
, 4 5 90 3
, 11 2 4 6
, 4 5 6 7
.
Then we applied diagonal calculation in these forms:
d1 = arr[0][0] + arr[1][1] + arr[2][2] + arr[3][3]
d2 = arr[0][3] + arr[1][2] + arr[2][1] + arr[3][0]
If d1 is greater then d2, then df = d1 - d2 otherwise df = d2 - d1.
Diagonal Difference C++ Program using For loop
// Diagonal Difference C++ Program using For loop
#include <iostream>
using namespace std;
int main() {
int s = 0;
cout << "Enter the size of the array::\n";
cin >> s;
int arr[s][s];
cout << "\nEnter the elements of the array in [" << s << " x " << s << "] matrix form::\n";
int i=0;
for (; i<s; i++) {
int j=0;
for (; j<s; j++) {
cin >> arr[i][j];
}
}
// It will calculate the diagonal difference
int df = 0, s2=s-1, d1=0, d2=0;
i=0;
for (; i<s; i++) {
d1 += arr[i][i];
d2 += arr[i][s2];
s2--;
}
df = d1 > d2 ? d1 - d2 : d2 - d1;
// It will return the final output
cout << "\nDiagonal Difference = " << df << "\n";
return 0;
}