1#include <stdio.h>
2void main ()
3{
4 int i,j,matrix[10][10],m,n,sum=0;
5
6 printf("Enter number of rows of matrix : ");
7 scanf("%d", &m);
8 printf("Enter number of columns of matrix : ");
9 scanf("%d", &n);
10
11 printf("\n");
12
13 if(m==n)
14 {
15 for (i = 0; i < m; i++)
16 {
17 for (j = 0; j < n; j++)
18 {
19 printf("Enter element of matrix [%d][%d]: ", i, j);
20 scanf("%d", &matrix[i][j]);
21 }
22 }
23
24 printf("\n");
25
26 for(i=0;i<m;i++)
27 {
28 for(j=0;j<n;j++)
29 {
30 if(i==j)
31 {
32 sum=sum+matrix[i][j];
33 }
34 }
35 }
36
37 printf("The sum of diagonal elements of the matrix = %d\n",sum);
38 }
39
40 else
41 printf("The matrix does not have diagonal elements");
42}
43
44
45
1#include<stdio.h>
2
3void main()
4{
5 int mat[12][12];
6 int i,j,row,col,sum=0;
7 printf("Enter the number of rows and columns for 1st matrix\n");
8 scanf("%d%d",&row,&col);
9 printf("Enter the elements of the matrix\n");
10 for(i=0;i<row;i++)
11 {
12 for(j=0;j<col;j++)
13 {
14 scanf("%d",&mat[i][j]);
15 }
16 }
17
18 printf("The matrix\n");
19 for(i=0;i<row;i++)
20 {
21 for(j=0;j<col;j++)
22 {
23 printf("%d\t",mat[i][j]);
24 }
25 printf("\n");
26 }
27 //To add diagonal elements
28 for(i=0;i<row;i++)
29 {
30 for(j=0;j<col;j++)
31 {
32 if(i==j)
33 {
34 sum=sum+mat[i][j];
35 }
36 }
37 }
38
39 printf("The sum of diagonal elements of a square matrix = %d\n",sum);
40}
41