[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 297
  • Last Modified:

Your Preference? For or While Loops

Hi, just looking to get some feedback on what programmers out there prefer and if they have any opinons about when to use on or the other. I've searched and have only been able to find what the two do and very little reasoning of why to use one or the other. For loops seem to be cleaner and have everything in one line, IMHO. I just can't see when you would prefer a while over it. Looking for a good discussion.
thanks, m.
0
unityxx311
Asked:
unityxx311
4 Solutions
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi unityxx311,

Both have their place.

In general, use while() if you want a continuous loop, or have several mutually exclusive exit conditions.  Use for() when you are looping through an object (or set of objects) according to an index.

These aren't "gospel", but a good set of guidelines.


Kent
0
 
imladrisCommented:
Not all loops are of the iterative sort. For instance, suppose you're parsing your way through a message. I wrote something like:

while(!msgEnded())
{   t=msgType();
    switch(t)
    {     case TYPE1:
                  ....
          case TYPE2:
                 ...
                 ...
                 ...
    }
}


In this case, since there is no need for an iterator variable, the while is sufficient.
0
 
bookiCommented:
unityxx311,

also note that the for loop can mimick the while loop

while (fCondition) {
  ...
}

is the same as.

for (;fCondition;) {
  ...
}

b.
0
 
anupvijayCommented:
It actually depends a lot on the developer himself who designs the code for specific requirement
of his.
I prefer using for loops when I know before hand the number of iterations it will take.
And when I need to loop depending on the status of some flag then I prefer while loop.
Like in the case of reading from a file will EOF.

A favorite usage of while loop is in a message queue application in the form while(TRUE){}

And of course I even prefer going the recursive way for fewer iterations instead of 'for' loops
sometimes.

Cheers,
Anup
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now