0
What are the advantages and disadvantages of various loops? Which one is your favorite?
I just started learning my first coding language ( C++) and I see there are various kinds of loops ( for, while, do while etc). I think I saw something similar in Javascript and Python. So I want to the advantage of using a particular type of loop over the others. Also which is the type of loop you use most often?
3 odpowiedzi
+ 3
Every loops is best.it depends upon your code which loop should you use in your code.every loop has same work run the code again and again.but these loops run the code in different styles and patterns.
you need to choose while loop in your code when you are checking condition means if condition is False then loop stops if true then run.
e.g
x=1
while x<6:
print(x)
x+=1
when x>5 loop stops.
you need to choose for loop if you want to run your code again and again at some range.means 2 to 9.
e.g
for i in range(10):
print(i) #loop run 0 to 9.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time although condition is False.
in do while loop code run first then condition check.
e.g
i = 1
while True:
print(i)
i = i + 1
if(i > 3):
break #here code run first then condition check using if statement and while is always be true.in python there is no do while loop so we just create our logic.
+ 2
My take : while and do while are equivalent (do while only means that the loop needs to be run at least once, whatever the case, so it saves a few lines when it is the case).
You can emulate any "for" loop with a "while", so you know you can always come back to a while statement.
BUUUUT, a "for" loop is easier to use and less prone to errors : often we might forget to increment the variable in the while, or we might have a difficult time to correctly define the exit condition in the while.
tl;dr version : if it is a simple recurrence job (with an integer, on a list or whatever) use a for loop, saves time and energy. If it's more complicated, use "while" and even if it happens to be a problem you could have solved with a for loop, using the while helps (forces ? ) conceptualize and define the problem.
+ 2
I think it is not merely a matter of preference; you choose the type of loop that fits the job best.
If you know the number of times you need to do something, use 'for'.
If you can't tell the number of times but know when to stop, you use 'while' or 'do while'.
There are differences between languages. For example there is no 'do while' in Python.
When I have the choice between different paths, I would try to take what's shortest (lines of code and efficiency) and easiest to read.