# C Program to find Sum of Diagonal Elements of a Matrix

How to write a C Program to find Sum of Diagonal Elements of a Matrix?. Or, How to write a C program to find Sum of Diagonal Elements of a Multi-Dimensional Array with example.

## C Program to find Sum of Diagonal Elements of a Matrix

This program allows the user to enter the number of rows and columns of a Matrix. Next, we are going to calculate the sum of diagonal elements in this matrix using For Loop.

```/* C Program to find Sum of Diagonal Elements of a Matrix */

#include<stdio.h>

int main()
{
int i, j, rows, columns, a, Sum = 0;

printf("\n Please Enter Number of rows and columns  :  ");
scanf("%d %d", &i, &j);

printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &a[rows][columns]);
}
}

for(rows = 0; rows < i; rows++)
{
Sum = Sum + a[rows][rows];
}

printf("\n The Sum of Diagonal Elements of a Matrix =  %d", Sum );

return 0;
}```

In this C Program to find Sum of Diagonal Elements of a Matrix example, We declared single Two dimensional arrays Multiplication of size of 10 * 10. The below statements ask the User to enter the Matrix size (Number of rows and columns. For instance 2 Rows, 3 Columns = a )

```printf("\n Please Enter Number of rows and columns  :  ");
scanf("%d %d", &i, &j);```

Next, we used C Programming for loop to iterate every cell present in a matrix. Conditions inside the for loops ((rows < i) and (columns < j)) will ensure the program compiler, not to exceed the Matrix limit. Otherwise, the matrix will overflow. The scanf statement inside the for loop will store the user entered values in every individual array element such as a, a, …..

```for(rows = 0; rows < i; rows++).
{
for(columns = 0; columns < j; columns++)
{
scanf("%d", &a[rows][columns]);
}
}```

In the next line, We have one more for loop to find Sum of Diagonal Elements of a Matrix

```for(rows = 0; rows < i; rows++)
{
Sum = Sum + a[rows][rows];
}```

User inserted values for C Program to find Sum of Diagonal Elements of a Multi-Dimensional Array example are: a = {{10, 20, 30}, { 40, 50, 60}, {70, 80, 90}}
Row First Iteration: for(rows = 0; rows < 3; 0++)
The condition (0 < 3) is True.
Sum  = Sum + a[rows][rows]
Sum  = Sum + a  => 0 + 10 = 10

Row Second Iteration: for(rows = 1; rows < 3; 1++)
The condition (1 < 3) is True.
Sum  = Sum + a
Sum  = 10 + 50 = 60

Row Second Iteration: for(rows = 2; rows < 3; 2++)
The condition (2 < 3) is True.
Sum  = Sum + a
Sum  = 60 + 90 = 150

Next, rows value will increment. After the increment, the condition inside the for loop (rows < 3) will fail. So it will exit from the loop. At last, we used the printf statement to print the total Sum as output.