0
are all while loops convertible to for loops?
earlier, I thought that we can't use for loops when working with linked lists... but then `for(current = head; current != NULL; current = current->next)` this line made me think. is all while loops are convertible to for loops especially when there is more than one condition?
2 Réponses
+ 2
It depends on what you mean by convertible.
In general I would say yes, if you make according adjustments.
Have a look at this code for example:
https://code.sololearn.com/csoeJwkO7MB7/?ref=app
If you don't write i++ before continue in the while loop, it will not update the iteration variable and therefore create an infinite loop, different from the for loop which will always update.
Also the scope of i is different in both cases.
While i exists only for the for loop if you declare it in its header, the i of while loop will be available after the while loop finished.
However it is better and most of times more efficient to use the appropriate loop.
So using for loops for known number of iterations and while loops for unkown number of iterations.
+ 1
Yes, they are algorithmically equivalent.