C Program: Sum of Both Diagonal of Matrix (User Defined Function)


Question: Write a program in C to read square matrix of order n and find sum of both diagonals using user defined function.


#include<stdio.h>

float diagsum(float a[10][10], int n);

int main()
{
 int i,j,n;
 float a[10][10], res;

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

 printf("Enter matrix elements:\n");
 for(i=0;i< n;i++)
 {
  for(j=0;j< n;j++)
  {
   printf("a[%d][%d]=",i,j);
   scanf("%f", &a[i][j]);
  }
 }
 res = diagsum(a,n);
 printf("Sum = %f\n", res);

}


float diagsum(float a[10][10], int n)
{
 int i,j;
 float s=0;
 for(i=0;i< n;i++)
 {
  for(j=0;j< n;j++)
  {
   if(i==j || i+j==n-1)
   {
    s = s+ a[i][j];
   }
  }
 }
 return(s);
}