/*Write a program to calculate sum of diagonal elements of square matrix using function. The function should return total sum to calling function. Program tested on debain testing with gcc version 9.3.0 */
The program works fine when used without function but there is problem i.e the passed array does not have all the elements of the original array and so the sum is incorrect.
#include <stdio.h>
#include <stdlib.h>
int sum(int a[10][10],int d);
int main(){
int r,c;
puts("Enter the dimension of square matrix");
scanf("%d %d",&r,&c);
if (r != c) {puts("Not a square matrix");exit(0);}//check if square matrix
int a[r][c];
puts("Enter the elements of the matrix");
for(int i=0; i<r; ++i){
for(int j=0; j<c; ++j){
printf("Enter a[%d][%d] element = ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
int result = sum(a,r);
printf("Sum of diagonal elements = %d \n",result);
return 0;
}
int sum(int a[10][10],int d){
//for a square matrix no of diagonal element = row/col of matrix
int result=0;
for(int i=0; i<d; ++i){
result=result+a[i][i];
}
return result;
}
10forrand10forcfor this to have any chance of working.