开发者

2-dimensional matrix

whats the logic to find the sum of 开发者_C百科alternate elements of a two-dimensional matrix.


//arr is the 2 D array MxN
int sum = 0;
for(int j=0;j<N;j++)
{
  for(int i=j&1;i<M;i+=2)
  {
      sum += a[i][j];
  }
}


you could cast the 2D array into 1-D array and do the summation in a loop.

int *a = (int*)arr; //arr being the 2 D array
int sum = 0;
for(int i=0;i<M*N;i+=2)
{
   sum += a[i];
}


 for (int i = 0; i < N; ++ i)
   for (int j = i%2; j < M; j += 2) {
     std::cout << i << "," << j << std::endl;
     sum += a[i][j];
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜