The while loop is the more general one because its loop condition is more flexible and can be more complicated than that of a for loop. The condition of a for loop is always the same and implicit in the construction. A for
loop stops if there are no more elements in the collection to treat.
For simple traversals or iterations over index ranges it is a good
advice to use the for statement because it handles the iteration variable for you, so it is more secure than while where you have to handle the end of the iteration and the change of the iteration variable by yourself.
The while
loop can take every boolean expression as condition and permits
therefore more complex end conditions. It is also the better choice if
the iteration variable does not change evently by the same step or if
there are more than one iteration variable. Even if you can handle more
than one iteration variable in a for statement, the collections from which to choose the values must have the same number of elements.
90 views
Usually answered in minutes!
×