I have the following question that I'm having trouble with.
I need write a code that defines some 2D array NxN that gets a number n (n can't be larger than N) which then defines a matrix nxn (starting from the 0,0 element to n,n) that I provide its elements. Then, the following calculation is done on the (i,j) cell and is placed in the (i,j) cell of another 2D array (which includes the output) of size nxn as well:
For every (i,j) in the input sub-matrix (nxn), I need write the average of all the cells above and to the left of the current cell including it and place it in (i,j) of the output matrix. For example, if n=3 and the input sub-matrix is
15 13 0
14 2 9
-3 12 -16
The output is
15.00 14.00 9.33
14.50 11.00 8.83
8.67 8.83 5.11
I was successful with the (0,j) (i,0) cells of the output matrix but in the rest (when both i and j arent 0) I'm always missing the cells that are diagonal to the one I'm looking at or more. This is a part of the code I've written that includes the calculations and the output matrix:
Code:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
sum=a[0][0];
cells=1;
if( i==0&& j>0)
{
for(k=1;k<=j;k++)
{
sum+=a[i][k];
cells++;
}
}
if( i>0&& j==0)
{
for(k=1;k<=i;k++)
{
sum+=a[k][j];
cells++;
}
}
if( i>0&& j>0)
{
}
b[i][j]=sum/cells;
}
}
printf("Result matrix:\n");
for(i =0; i < n; i++){
for(j =0; j < n; j++){
printf("%d ", b[i][j]);
}
printf("\n");
}
I left the last if condition empty on purpose as my attempts failed.
I apologize in advance if something isn't clear. I will make sure to explain better if someone got lost in my explanation.
Any help would be much appreciated. Thank you. |