C Program to find sum of diagonal elements of a matrix


In this program, You will learn how to find sum of diagonal elements of a matrix in c.


1 2 3

4 5 6

7 8 9

1 + 5 + 9 = 15


Example: How to find sum of diagonal elements of a matrix in c

Run it Now
#include<stdio.h>

int main() {

 int arr[10][10];
 int n,i,j,sum=0;

 printf("Enter Size of Matrix :");
 scanf("%d",&n);

 printf("\nEnter Matrix Elements :");

 for (i = 0; i < n; i++) {
     for(j = 0; j < n;j++){
         scanf("%d", &arr[i][j]);
     }
 }

 printf("\nAll Matrix Elements :\n");
 for (i = 0; i < n; i++) {
     for(j = 0; j < n; j++){
         printf("%d ", arr[i][j]);
     }
     printf("\n");
 }

printf("List is: ");
 for(i = 0; i < n; i++){
     printf("%d ",arr[i][i]);
     sum = sum + arr[i][i];
 }
 printf("\nSum of Diagonal is :%d", sum);

 return 0;
}

Output:

Enter Size of Matrix :3
Enter Matrix Elements :1 2 3 4 5 6 7 8 9
All Matrix Elements :
1 2 3
4 5 6
7 8 9
List is: 1 5 9
Sum of Diagonal is :15