#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m,n,i,j,k,imp_sum, par_sum,temp,a[100][100];
void calc_rand()
{
srand(time(NULL));
printf("Number of rows and columns:");
scanf("%d %d", &m, &n);
int a[m][n];
for (i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
a[i][j]=(rand()%25)-5;
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
void calc_num()
{
for (i=0; i<n; i++)
{
par_sum=0;
imp_sum=0;
for(j=0; j<m; j+=2)
{
if (a[j][i]<0)
{
par_sum=par_sum+abs(a[j][i]);
}
}
printf("\nSum of emelents <0 %d on even position: %d",i+1, par_sum);
for(j=1; j<m; j+=2)
{
if(a[j][i]>0)
{
imp_sum=imp_sum+a[j][i];
}
}
printf("\nSum of elements >0 %d on odd position: %d",i+1, imp_sum);
}
}
int main()
{
calc_rand();
calc_num();
return 0;
}
I'm new to using functions and I've encountered a problem. When trying to figure out the sum of the elements I need above (I do that in the second function named calc_num
) it always returns me 0, and I don't really understand why that happens.
In calc_rand
, you're creating a new array called a
locally which masks the global variable a
. This results in the local a
being updated instead of the global a
.
Remove the int a[m][n];
declaration inside calc_rand
and it will update the global array.