The best bet would be to use pointers. Since you want to use a single loop, it would require using a different logic. Posting the answer first:
double* p = &mat[0][0];
for (int i = 0; i < 36; i++)
sum += *(*(p+ int(i/6)) + i%6)+ 48;
Pointers for 2D arrays work in the following manner. Consider a int matrix[3][3]
:
matrix => Points to base address of two-dimensional array.
Since array decays to pointer.
*(matrix) => Points to first row of two-dimensional array.
*(matrix + 0) => Points to first row of two-dimensional array.
*(matrix + 1) => Points to second row of two-dimensional array.
**matrix => Points to matrix[0][0]
*(*(matrix + 0)) => Points to matrix[0][0]
*(*(matrix + 0) + 0) => Points to matrix[0][0]
*(*matrix + 1) => Points to matrix[0][1]
*(*(matrix + 0) + 1) => Points to matrix[0][1]
*(*(matrix + 2) + 2) => Points to matrix[2][2]
So the code works as follows:
*(*(p+ int(i/6)) + i%6)
on i=0
gives *(*(p+ 0) + 0)
*(*(p+ int(i/6)) + i%6)
on i=1
gives *(*(p+ 0) + 1)
*(*(p+ int(i/6)) + i%6)
on i=2
gives *(*(p+ 0) + 2)
and the loop goes upto i=35
.