Originally posted by arifin rusli:
Hello people,
i am immediately thinking about the loop while,for and do while. When should i use while, when to use for and when to use do while.
As far as i know all is the same, but what is the benifit from each other, when to use for loop is better than while loop or do while loop. Thanks for any help.
I think that what Mark is trying to say is that you don't need the if statements in any of these constructs. Instead, you can write these loops as
This will make your code much easier to understand, in my opinion.
As to your question, the for loop is typically used to count the number of times you want to repeat something. This means that you usually need to know exactly how many times you want to repeat. The while loop on the other hand is usually used when you don't know the exact number of times to repeat. Instead, you have a flag that indicates when you want to stop. Finally, the do while statement is useful when you know you need to do something at least once. Personally, I don't find the while loop very useful in practice.
Layne