‘C’ program to calculate the sum of diagonal elements of matrix.

C File =>


/* Write a ‘C’ program to read a matrix and calculate the sum of its diagonal 
elements. */

#include<stdio.h>
int main() 
{
     int mat[30][30],sum=0,i,j,m,n;
 
     printf("\n Enter how many rows?");
     scanf("%d",&m);
     printf("\n Enter how many cols?");
     scanf("%d",&n);
 
     printf("\n Input matrix");
     for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
       {
           printf("\n Enter element %d%d",i+1,j+1);
          scanf("%d",&mat[i][j]);
        }
    }
 
    printf("\n\n Given matrix is\n");
    for(i=0;i<m;i++)
   {
      for(j=0;j<n;j++)
     {
        printf("%d\t",mat[i][j]);
        
        if(i==j)
           sum=sum+mat[i][j];
      }
      printf("\n");
    }
 
    printf("\n Sum of diagonal : %d",sum);
 
    return 0;
}

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.