Types of Loops (and when to use them)


#1

As I finished Chapter 7, I am curious of the three types of loops and if there are rules, standards, or instances where you should choose one over another?

To me it seems:

FOR loop is the power lifter and the one I would choose most often in most circumstances.

DO WHILE loop is used when you want to execute the code one time before checking condition, but otherwise used rarely.

WHILE loop is where I cannot figure out when I would use it over/before the other two.

Any thoughts appreciated.


#2

You’re pretty close.

FOR is indeed the power lifter and I use it any time I need to loop in a situation where I care which iteration I’m on, which is usually the case.

WHILE - I use this any time I need to loop over code but don’t care about the iteration or number of times it’s happening. This is useful when the thing you want to do has a chance of changing the condition on which you want to do it: while (THING is true) {do something that may cause THING to become false}.

DO WHILE - I use this when I want a WHILE loop, but need to guarantee that the conditional code will run at least once. I’d say I use this least frequently of the three.