0
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?
4
Contributors
5
Replies
19
Views
4 Years
Discussion Span
Last Post by mike_2000_17
0

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 by Ancient Dragon

0

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.