sum of diagonal elements of a matrix in c
#include <stdio.h>
void main ()
{
int i,j,matrix[10][10],m,n,sum=0;
printf("Enter number of rows of matrix : ");
scanf("%d", &m);
printf("Enter number of columns of matrix : ");
scanf("%d", &n);
printf("\n");
if(m==n)
{
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("Enter element of matrix [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
printf("\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
sum=sum+matrix[i][j];
}
}
}
printf("The sum of diagonal elements of the matrix = %d\n",sum);
}
else
printf("The matrix does not have diagonal elements");
}
3.75
4
#include<stdio.h>
void main()
{
int mat[12][12];
int i,j,row,col,sum=0;
printf("Enter the number of rows and columns for 1st matrix\n");
scanf("%d%d",&row,&col);
printf("Enter the elements of the matrix\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&mat[i][j]);
}
}
printf("The matrix\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
//To add diagonal elements
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(i==j)
{
sum=sum+mat[i][j];
}
}
}
printf("The sum of diagonal elements of a square matrix = %d\n",sum);
}
Thank you!
4
0
Are there any code examples left?
New code examples in category TypeScript
-
TypeScript 2022-03-27 19:30:45 typescript promise
-
TypeScript 2022-03-27 17:25:44 how to search for imports in vscode
-
TypeScript 2022-03-27 17:15:20 angular formgroup mark as touched
-
TypeScript 2022-03-27 17:05:06 use of slice and splice add elements array
-
TypeScript 2022-03-27 16:50:23 android studio loop through all objects in layout
-
TypeScript 2022-03-27 14:35:08 wergensherts meaning
-
TypeScript 2022-03-27 13:50:15 remove all the elements from a numpy array python
-
TypeScript 2022-03-27 12:35:49 redux toolkit typescript install
-
TypeScript 2022-03-27 12:35:30 laravel middleware for apis