A nested loop puzzle?


In this section we will see one interesting problem. We will see two code segments. Both are with two nested loops. We have to identify which one will run faster. (We will assume that the compiler is not optimizing the code).

Segment 1

for(int i = 0; i < 10; i++){
   for(int j = 0; j<100; j++){
      //code
   }
}

Segment 2

for(int i = 0; i < 100; i++){
   for(int j = 0; j<10; j++){
      //code
   }
}

Both codes will run the same number of times. The code inside two loops will execute 10000 times in both cases. But if we look carefully we can understand that the second code is doing more tasks than the first one. In the first code, the inner loop will be executed 10 times. So for initialization, condition checking, and increment operation will be executed 10 times. But for the second code, the inner loop will be executed 100 times. So initialization, condition checking, and the increment operation will be executed 100 times. So it will take a longer time than the first one.

Updated on: 31-Jul-2019

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements