Pages

Saturday, 11 July 2015

Sum of all diagonal elements

C Program to do the Sum of the Main & Opposite Diagonal elements of a matrix

Coding:
#include<stdio.h> #include<stdlib.h>
int main() { int **a,row,col,i,j,sum=0; printf("Please enter the total number of rows & columns of squre matrix:"); scanf("%d%d",&row,&col); if(row==col){ a=(int**)malloc(row*sizeof(int)); for(i=0;i<row;i++) a[i]=(int*)malloc(col*sizeof(int)); printf("Please enter the elements:\n"); for(i=0;i<row;i++) for(j=0;j<col;j++) scanf("%d",&a[i][j]); printf("Matrix elements before transforme:"); for(i=0;i<row;i++) { printf("\n"); for(j=0;j<col;j++) { printf("%d ",a[i][j]); } } for(i=0;i<row;i++) { for(j=0;j<col;j++) { if(i+j==row-1||i==j) { sum+=a[i][j]; } } } printf("\nSum of the diagonal elements=%d",sum); } else printf("It is not a square matrix"); return 0; } Output: Please enter the total number of rows & columns of square matrix:3 3 Please enter the elements: 1 2 3 4 5 6 7 8 9 Matrix elements before transform: 1 2 3 4 5 6 7 8 9 Sum of the diagonal elements=25