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[10][10], 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[2][3] )
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[3][3] matrix. Conditions inside the for loops ((rows < i) and (columns < j)) will ensure the C program compiler, not to exceed the C 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[0][0], a[0][1], …..
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[3][3] = {{10, 20, 30}, { 40, 50, 60}, {70, 80, 90}}. Refer to the Multi-Dimensional Array in C article.
Row First Iteration: for(rows = 0; rows < 3; 0++)
The condition (0 < 3) is True.
Sum = Sum + a[rows][rows]
Sum = Sum + a[0][0] => 0 + 10 = 10
Row Second Iteration: for(rows = 1; rows < 3; 1++)
The condition (1 < 3) is True.
Sum = Sum + a[1][1]
Sum = 10 + 50 = 60
Row Second Iteration: for(rows = 2; rows < 3; 2++)
The condition (2 < 3) is True.
Sum = Sum + a[2][2]
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.
Also Read
- C Program to Find the Sum of each and every Row and Column in a Matrix
- C Program to Find the Sum of each row in a Matrix
Comments are closed.