Home > Mobile >  How to count sum of elements located in the upper left quarter of matrix
How to count sum of elements located in the upper left quarter of matrix

Time:03-10

double CountSum(double **mat, int R, int C)
{
   double sum = 0.0;
   for(int i = 0; i < R / 2; i  )
   { 
     for(int j = 0; j < C / 2; j  )
     { 

         sum  = mat[i][j];
     }
   }
   return sum;
}

Am I correct do this, or where I have mistakes? Or if you have some piece of advice on how to pass parameters to function, please tell me about that

CodePudding user response:

Assuming R and C are number of rows and number of columns respectively, this code won't work.

If R = 2 then (R - 1) / 2 = 0 so the outer loop won't be executed, because i < 0 is always false.

Don't subtract one, R / 2 would be enough. There are corner cases though, when R and C aren't even.

About parameters: you can add R and C to parameter list instead of i and j. (double **mat, int R, int C) and pass them respectively. From this current code, it looks like they are just global variables. i and j can be declared inside the function.

Code:

double CountSum(double **mat, int R, int C)
{
   double sum = 0.0;
   for(int i = 0; i < R / 2; i  )
   { 
     for(int j = 0; j < C / 2; j  )
     { 

         sum  = mat[i][j];
     }
   }
   return sum;
}

This is the working code, I hope you understand how to use it - pass it an appropriate arguments. R and C being height and width of the matrix or dimensions can be called as well. Note that if R or C or both are odd, then you only get the sum of the smaller part always, if you want the bigger part, you should ceil it, thus use (R 1) / 2 instead of R / 2 and similar for C.

CodePudding user response:

First, why are you passing i and j in CountSum() ? You set it after , in for loop.

After that you should look your for loops when R = 1 or R = 2 you will not enter to the loop.

Finally in C/C when you pass array pointer you should pass two parameters more, this parameters are the dimensions of the array.

  • Related