Courses βeta
C Programming

## A nested loop puzzle

Which of the following two code segments is faster? Assume that compiler makes no optimizations.

/* FIRST */
for(i=0;i<10;i++)
for(j=0;j<100;j++)
//do somthing

/* SECOND */
for(i=0;i<100;i++)
for(j=0;j<10;j++)
//do something


Both code segments provide same functionality, and the code inside the two for loops would be executed same number of times in both code segments.
If we take a closer look then we can see that the SECOND does more operations than the FIRST. It executes all three parts (assignment, comparison and increment) of the for loop more times than the corresponding parts of FIRST

a) The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times.
b) The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100). c) The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation.

Below C++ code counts the number of increment operations executed in FIRST and SECOND, and prints the counts.

/* program to count number of increment operations in FIRST and SECOND */
#include<stdio.h>

int main()
{
int c1 = 0, c2 = 0 , i , j;

/* FIRST */
for(i=0;i<10;i++,c1++)
for(j=0;j<100;j++, c1++);
//do something

/* SECOND */
for(i=0; i<100; i++, c2++)
for(j=0; j<10; j++, c2++);
//do something

printf(" Count in FIRST = %d\n",c1);
printf(" Count in SECOND  =%d\n", c2);

getchar();
return 0;
}


Below C++ code counts the number of comparison operations executed by FIRST and SECOND

/* Program to count the number of comparison operations executed by FIRST and SECOND */
#include<stdio.h>

int main()
{
int c1 = 0, c2 = 0, i , j;

/* FIRST */
for(i=0; ++c1 && i<10; i++)
for(j=0; ++c1 &&j<100;j++);
//do something

/* SECOND */
for(i=0; ++c2&&i<100; i++)
for( j=0; ++c2&&j<10; j++);
//do something

printf(" Count fot FIRST  %d\n" ,c1 );
printf(" Count fot SECOND  %d\n", c2);
getchar();
return 0;
}