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


In this program, You will learn how to find the 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 the sum of diagonal elements of a matrix in c.

#include<stdio.h>

int main() {

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

 printf("Enter size of matrix:");
 scanf("%d",&n);

 printf("Enter matrix elements:");

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

 printf("All 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 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