SOFUser - 10 months ago 44

C Question

I have written a function for calculating multiplication of 2 matrices.

This is the function :

`int entrycal(int i,int j,int m,int n,int k,int a[m][n],int b[n][k],int q) {`

static int sum = 0;

sum += a[i][q] * b[q][j];

if ( q+1 < n )

entrycal(i,j,m,n,k,a,b,q+1);

return sum;

}

I have tried using static int , but when I need to calculate a new entry (after returning sum and calling the function again from the main function ) ,it doesn't get initialized to zero.

I have solved the problem using a global variable "sum" and initializing it in the main function every time I call the "entrycal" function, but I like to solve it without using global variables.Is it possible ?

secondary question :

If there is a problem with my function arguments and they can get better I would be happy to learn more!

sorry for my english

thanks

Answer Source

To directly answer your question:

```
int entrycal(int i,int j,int m,int n,int k,int a[m][n],int b[n][k],int q) {
static int sum = 0;
int total_sum = 0;
sum += a[i][q] * b[q][j];
if ( q+1 < n )
entrycal(i,j,m,n,k,a,b,q+1);
total_sum = sum;
sum = 0;
return total_sum;
}
```

However I would implement it like:

```
int entrycal(int i,int j,int m,int n,int k,int a[m][n],int b[n][k],int q) {
int sum = a[i][q] * b[q][j];
if ( q+1 < n )
return sum + entrycal(i,j,m,n,k,a,b,q+1);
return sum;
}
```