For initialising all the elements of a 100×100 two-dimensional array, we can do it in two ways:
Method 1:
int a[100][100];
for(i=0; i<100; i++){
for(j=0; j<100; j++){
a[i][j] = 10;
}
}
Method 2:
int a[100][100];
for(j=0; j<100; j++){
for(i=0; i<100; i++){
a[i][j] = 10;
}
}
Now my question is which of the method is more efficient and why?
The first method, since that will access the array sequentially.
C stores 2-dimensional arrays in row-major order, meaning that a[i][j] will be adjacent to a[i][j+1] but not adjacent to a[i+1][j].
Yet another way to say the same thing (that generalizes to >2 dimensions) is that the rightmost index is adjacent in memory. Or that incrementing an index means that you have to jump past all the dimensions to the right of the index you’re incrementing.