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];
}
精彩评论