Which is faster: while loop or for loop ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Which is faster: while loop or for loop ?

5th Jul 2020, 4:21 PM
Samir
Samir - avatar
2 Answers
+ 3
In Data Structres and Algorithms, the running time of while loop and for loop are the same, so no one is faster, what it really depends on, is what you are doing with them. For example, assume you have a list [K] and an Element you are searching for let us take e. Now you write two codes K =[1,2,3,4] e = 4 #---for loop for i in K: if i == e: print(i) break #--- #---while loop Ctr =0 while(True): if K[Ctr] == e: print(e) break In Informatics we analyze the code like the following, based on mathematical approach: we have a list of length n we have an element e we have a sorted list now every operation like + - or assignment takes the complexity of O(1) (O notation) and does not count to runtime as it is a constant. So let us analyze the for loop, the for loop has 3 cases: Worst Case: O(n) #we have to go through the wohle list(through n elements) to find the element Best Case: O(1) #element is at the beginning of the list Average Case(little bit Complex to compute) O(n) is linear
5th Jul 2020, 4:56 PM
William M
William M - avatar
+ 3
Continuing... Now analyze while loop: The while loop increments Ctr every round which takes O(1) which we have to throw away. So the while loop searches a list K for the element (e) consisting of n elements: Complexity: Worst Case: O(n)#search whole list Best Case: O(1)#element found at beginning Average Case: O(litte bit complex to compute) So now after analyzing two loops, we see, that both of the loops have the same performance... but another implementation, so now you can say, the implementation of while-loop is in some cases much flexible than the for-loop, and not faster!
5th Jul 2020, 5:00 PM
William M
William M - avatar