Program to calculate sum of diagonal elements of matrix


C File =>


/* Write a C program to accept and display a matrix of order nXn. Use dynamic memory allocation. Also calculate sum of diagonal elements. */


#include<stdio.h>
#include<stdlib.h>
int main()
{
     int n,i,j,*ptr[50],sum=0;
     printf("\n Enter order of matrix : ");
     scanf("%d",&n);
    // dynamic allocation of memory
     for(i=0;i<n;i++)
         ptr[i]=(int*)malloc(n*sizeof(int));

    // Accepting matrix
     for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
      {
             printf("\n Enter matrix element a%d%d : ",i+1,j+1);
             scanf("%d",&ptr[i][j]);
       }
    }
    printf("\n\n Given Matrix is : \n ");
    for(i=0;i<n;i++)
   {
       for(j=0;j<n;j++)
          printf("%d\t",ptr[i][j]);
       printf("\n");
    }
  // Calculating sum of diagonal
    for(i=0;i<n;i++)
  {
     for(j=0;j<n;j++)
    {
        if(i==j)
           sum=sum+ptr[i][j];
      }
   }
   printf("\n Sum of diagonal elements = %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”.