Diagonal Difference in C Program
Diagonal difference in C program.
In this article, you will learn how to make a diagonal difference in C program.
Example
Enter the size of the array::
4
Enter the elements of the array in [4 x 4] matrix form::
11 2 4 6
4 5 6 7
10 8 -12 2
4 5 90 3
Diagonal Difference = 15
You should have knowledge of the following topics in c programming to understand this program:
- C
main()
function - C
printf()
function - C
while
loop - C
for
loop
Source Code
// Diagonal Difference in C Program
#include <stdio.h>
int main() {
int s = 0;
printf("Enter the size of the array::\n");
scanf("%d", &s);
int arr[s][s];
printf("\nEnter the elements of the array in [%d x %d] matrix form::\n", s, s);
int i=0;
while (i<s) {
int j=0;
while (j<s) {
scanf("%d", &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
printf("\nDiagonal Difference = %d\n", df);
return 0;
}
Output
Enter the size of the array::
4
Enter the elements of the array in [4 x 4] matrix form::
11 2 4 6
4 5 6 7
10 8 -12 2
4 5 90 3
Diagonal Difference = 15
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: 11 2 4 6
, 4 5 6 7
, 10 8 -12 2
, 4 5 90 3
.
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 in C Program using For loop
// Diagonal Difference in C Program using For loop
#include <stdio.h>
int main() {
int s = 0;
printf("Enter the size of the array::\n");
scanf("%d", &s);
int arr[s][s];
printf("\nEnter the elements of the array in [%d x %d] matrix form::\n", s, s);
int i=0;
for (; i<s; i++) {
int j=0;
for (; j<s; j++) {
scanf("%d", &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
printf("\nDiagonal Difference = %d\n", df);
return 0;
}