In this tutorial, we will learn how to write C Program to find the Sum of Diagonals of Matrix. as the matrix contains two diagonals, we will consider one as the** main **and another as the** opposite**.

**Note **that the number of rows and number of columns of a matrix must be equal that is it should be 2×2 or 3×3, etc. In other words, the matrix must be a square matrix.

We will look through the C program and find the sum of the main & opposite diagonal elements of an MxN Matrix. For example:

Consider a matrix of 2×2 matrix,

2 3

6 5**Output:**

Sum of the main diagonals = 2+5 = **7**

Sum of the opposite diagonals = 3+6 =** 9**

**C Program to find the sum of the diagonal elements in a matrix**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> void main() { int arr[10][10]; int i, j, m, n, sum1 = 0, sum2 = 0; printf("Enter the order of the matix: "); scanf("%d %d", &m, &n); //Checking the condition to see if m is equal to n if (m == n) { printf("Enter the elements for the matrix: \n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { scanf("%d", &arr[i][j]); } } // Adding the diagonals for (i = 0; i < m; ++i) { sum1 = sum1 + arr[i][i]; sum2 = sum2 + arr[i][m - i - 1]; } printf("\nThe sum of the main diagonal: %d\n", sum1); printf("The sum of the opposite diagonal: %d\n", sum2); } else printf("The order entered is not square matrix."); } |

**Output:**

As you can see in the program that **if..else statement** has been used to check if the order entered is a square matrix or not (** m == n**).