We have a 2-dimensional table with doubles. We want to change each value to the average (based on itself and the surrounding cells).

eg.
5 6 7
7 8 7
9 3 1

The cell with the number 8 will become = (5+6+7+7+8+7+9+3+1)/9
The cell with the number 5 will become = (5+6+8+7)/4

Below you will find the 2 required from the exercise functions and the 1 that was optional.
In addition i included the main() function just for you to be able to easily test the code.

1
2
3
4
#include <stdio.h>

#define NROWS 2
#define NCOLS 3

This is the optional function that checks if a cell around our cell-to-be-checked is inside the RxC table

1
2
3
4
5
int check(int r,int c){
    if(r<0 || r>NROWS-1 || c<0 || c>NCOLS-1)
        return 0;
    return 1;
}

Requirement 1: calculates the average of the cell according the cells around

1
2
3
4
5
6
7
8
9
10
11
12
double avg(double grid[NROWS][NCOLS],int r,int c){
    int k,l,divisor=0;
    double average=0;
    for(k=r-1;k<r+2;k++){ //for the 3 rows of 3x3
        for(l=c-1;l<c+2;l++) //for the 3 columns 3x3
            if(check(k,l)==1){ //it means it is a valid cell so we will include it in average
                average+=grid[k][l];
                divisor++;
            }
    }
    return average/divisor;
}

Requirement 2: Smooths the table calling the avg() above for each cell

1
2
3
4
5
6
7
8
9
10
11
12
void smooth(double grid[NROWS][NCOLS]){
    int i,j;
    double temp[NROWS][NCOLS];
   
    for(i=0;i<NROWS;i++) //for each row
        for(j=0;j<NCOLS;j++) //for each column
            temp[i][j]=avg(grid,i,j);
   
    for(i=0;i<NROWS;i++)
        for(j=0;j<NCOLS;j++)
            grid[i][j]=temp[i][j];
}

This is just for demonstration reasons. NOT needed by the exercise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
    double grid[NROWS][NCOLS]={1,2,3,4,5,6};
    int i,j;
   
    for(i=0;i<NROWS;i++)
        for(j=0;j<NCOLS;j++)
            printf("grid[%d][%d]: %f\n",i,j,grid[i][j]);
    smooth(grid);
    for(i=0;i<NROWS;i++)
        for(j=0;j<NCOLS;j++)
            printf("grid2[%d][%d]: %f\n",i,j,grid[i][j]);
           
    return 0;
}