Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
difference between while,dowhile and for loop? which loop is best?
Posted
Comments
Chris Maunder 27-Jul-11 11:30am    
Which is best? A hammer or a screwdriver?

They all work, but the one you use will depend on your requirements. for will loop over a known sequence, while will run until a condition is met, and do-while always runs once. Your best bet, is to buy a book and do exercises so you understand how each works.

If there was such a thing as 'best', and we should always use one, the language would not bother to ofer the others.

Edited to remove the ludicrous claim that C++ does not offer 'while', which was based on my memory of using C++ 6 years ago,and my state of jetlag......
 
Share this answer
 
v2
Comments
Maximilien 27-Jul-11 10:56am    
while exists in C++ ... or something changed since yesterday.
Christian Graus 27-Jul-11 10:58am    
Does it ? Hmmmm... I must be getting old.
Albert Holguin 27-Jul-11 11:10am    
my 5 of v2... let's keep ludicrous claims to a bare minimum... :)
Manas Bhardwaj 27-Jul-11 11:52am    
my 5
I like using the for loop when I want something to loop a known no. of times and when I have indices or pointers that I want to increment or decrement with each loop. Its useful for going through strings or arrays.

A while loop is good for when you want something to loop as long as some condition is true, even indefinitely, and/or if you want something that won't loop at all if the condition is false to start. This is because the test condition is tested at the begining of the loop.

A do while differs from the while in that it will execute once even if the condition is false to start with. This is because the condition is tested at the end of the loop.

Of course it depends on what you want the code to do as each of these can be used in various ways. A for loop can have no increments or starting values and just operate like a while. Or a while loop can have indices counting inside the loop that get tested at the end.

And don't forget you can use break and continue statements. Break exits out of a loop at any point, and continue jumps over any statements after it in the loop and continues looping.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900