which one should be preferable from the following two nested for loops:

1.
for(i=0;i<100;++i)
{
for(k=0;k<10000;++k)
{
<lines of code>
}
}

2.
for(k=0;k<10000;++k)
{
for(i=0;i<100;++i)
{
<lines of code>
}
}

why?

Example: Lets say you want to print out a multiplication table that has 10 rows and 5 columns. Rows are numbered 1 through 10 and columns numbered 1 through 5. The value in each column is the row number times the column number.

To print such a table you have to loop through each row, then inside that loop you have to loop through each column. It would be next to impossible to print the table if the two loops were reversed.

Edited 3 Years Ago by Ancient Dragon

Also, if accessing data in a large 2D array, you should generally order the looping so that you work across rows, not down columns.

For a very technical answer:

which one should be preferable from the following two nested for loops:

The one that results in the most predictable and contiguous memory accessing pattern, to minimize cache misses and maximize pre-fetching.

This question has already been answered. Start a new discussion instead.