Home > front end >  How to count sum of elements located in the upper left quarter of given matrix
How to count sum of elements located in the upper left quarter of given matrix

Time:03-10

double CountSum(double **mat, int i, int j)
{
   double sum = 0.0;
   for(i = 0; i < (R-1) / 2; i  )
   { 
     for(j = 0; j < (C-1) / 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.

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