Do you find it difficult to remember which loop you should use when developing? There are a few rules of thumb:
- If you have to iterate over a collection of elements the use of a for-each-loop is almost always the most elegant solution.
- If you need a loop that is not used for a collection but in example to repeat a certain action a few times the for-each-loop can not be used. In that case you have to choose between a for-loop and a while-loop. A for-each loop can only be used for collections.
- The for-loop is a good choice if the number of iterations is already known (how often the loop should be passed). This information can be stored within a variable but may not change while passing the loop.
- The while-loop is a good choice if the number of iterations is not known. The end of the loop can be determined by a condition. For example looping trough a file line by line till you reach the end of the file.
- If you iterate over a collection of elements and you want to remove an element out of the collection you should use a for-loop in combination with a Iterator if you want to go through the entire collection. You should use a while-loop if you want to discontinue execution of the loop before it has reached the end of the collection.
I do use these rules of thumb when developing applications in the JAVA programming language. Each language may have it’s own way of doing things best.