In the below code, When I did the same logic without using functions it gave correct answer. But with using functions its giving some junk value. The question was to print the sum of diagonal matrix in array using c using functions.
#include<stdio.h>
int read(int a[][100],int,int);
int displayres(int a[][100],int,int);
int main()
{
int m,n,a[100][100];
printf("Enter the number of rows: ");
scanf("%d",&m);
printf("Enter the number of columns: ");
scanf("%d",&n);
if(m==n)
read(a,m,n);
displayres(a,m,n);
}
int read(int a[][100],int m,int n)
{
int i,j;
if(m==n)
printf("Enter the elements:\n");
for(i=0;i<m;i )
{
for(j=0;j<n;j )
{
scanf("%d",&a[i][j]);
}
}
}
int displayres(int a[][100],int m,int n)
{
int i,j,abc;
for(i=0,j=0;i<m,j<n;i ,j )
{
abc = abc a[i][j];
}
printf("%d\n",abc);
}
CodePudding user response:
As the diagonal is processed for quadratic matrices then these declarations of the functions
int read(int a[][100],int,int);
int displayres(int a[][100],int,int);
do not make a great sense. One parameter is redundant. The functions can be declared like
void read(int a[][100], size_t );
int displayres(int a[][100], size_t );
correspondingly instead of these two prompts
printf("Enter the number of rows: ");
scanf("%d",&m);
printf("Enter the number of columns: ");
scanf("%d",&n);
you should use only one prompt and also you need to check that the entered number (for example n) is not greater than 100.
As the function read
returns nothing its return type should be void
.
Its definition can look like
void read(int a[][100], size_t n )
{
printf("Enter the elements:\n");
for ( size_t i = 0; i < n; i )
{
for ( size_t j = 0; j < n; j )
{
scanf("%d",&a[i][j]);
}
}
}
Within the function displayres
you forgot to initialize the variable abc
. And the function should not output anything. It should return the calculated value. The function can look the following way
int displayres(int a[][100], size_t n )
{
int abc = 0;
for ( size_t i = 0; i < n; i )
{
abc = a[i][i];
}
return abc;
}
And in main you can write
printf( "The sum is %d\n", displayres( a, n ) );
If you want to calculate the sum for a matrix of any sizes then the function displayres
can look the following way
int displayres( int a[][100], size_t m, size_t n )
{
int abc = 0;
for ( size_t; i < m && i < n; i )
{
abc = a[i][i];
}
return abc;
}
As for your for loop then you are using the comma operator in the condition
for(i=0,j=0;i<m,j<n;i ,j )
It is the same as to write
for( i=0, j=0; j < n; i ,j )
because the value of the first operand of the comma operator is discarded.