GATE | Sudo GATE 2020 Mock III (24 January 2019) | Question 38

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

Code-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Code-2:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


(A) Code-1
(B) Code-2
(C) Both are equal in speed.
(D) None of these.


Answer: (A)

Explanation: 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.

Refer – A nested loop puzzle.

Option (A) is correct.

Quiz of this Question

My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.