Sum of Principal Diagonal Elements of Square Matrix - C Program


Question: Write a program in C to read square matrix of order n and find sum of principal diagonal elements.

Sum of Principal Diagonal Elements Using C


#include<stdio.h>

int main()
{
 int i,j,n;
 float a[10][10], sum=0.0;

 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]);
  }
 }
 
 for(i=0;i< n;i++)
 {
  for(j=0;j< n;j++)
  {
   if(i==j)
   {
    sum = sum + a[i][j];
   }
  }
 }
 printf("Sum = %f\n", sum);
 
 return 0;
}