Monday, 16 October 2017

Matrix Diagonal Sum

Q : Write a ‘C’ program to find out sum of diagonal elements of a matrix using ‘C’.

Solution : 

#include<stdio.h>
#include<conio.h>
#define MAX 3
void main()
{
     int ar[MAX][MAX],i,j,r,c,sum=0;
     clrscr();
     for(r=0;r<MAX;r++)
     {
          for(c=0;c<MAX;c++)
          {
              printf("Enter Number>> ");
              scanf("%d",&ar[r][c]);
          }
     }
     printf("\n\tOutput\n\n");
     for(r=0;r<MAX;
r++)
     {
          for(c=0;c<MAX;c++)
          {
              printf("\t%d",ar[r][c]);
          }
          printf("\n");
     }
     for(r=0;r<MAX;r++)
     {
          for(c=0;c<MAX;c++)
          {
              if(c==r)
                   sum+=ar[r][c];
          }
     }
     printf("\n\tDiagona sum is %d",sum);
     getch();
}


Output



No comments:

Post a Comment