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?

Since both are the same, it will probably depend on what "<lines of code>" contains.

can you give an example as to how it will depend on the lines of codes

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.