Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
hassan

When To Use A Particular Type Of Loop?

Recommended Posts

Hi

 

On page 70 it discusses loops and states "The functionality of both loops is similar

enough that for and while can often be used interchangeably. Still, experience will  reveal that the for loop is a better choice for doing something a known number of times,
whereas while is used when a condition will  be true an unknown number of times."
 
I understand that the foreach loop will get everything in an array.
 
Where and when and why would you use a for loop instead of a while and vice-versa? (can someone give practical scenarios)?
 
Also where and when and why would you use a do while loop? what benefits does it have instead of using foreach or for or while loops?
 
Thanks in advance
 
 

Share this post


Link to post
Share on other sites

If you keep reading the book you'll see more and more examples, but the rule is the one you quoted: 

 

the for loop is a better choice for doing something a known number of times, whereas while is used when a condition will  be true an unknown number of times

 

 

So the while loop is normally used for reading through database query results, files, and network communications. The for loop and/or foreach, is used to iterate a known number of times, such as on an array.

Share this post


Link to post
Share on other sites

Ok thinking a bit more about it ... would we use the for loop for example when we want to display ten items from a data base and create mulitple pages showing ten items? like in a product catalog?

Share this post


Link to post
Share on other sites

If you keep reading, you'll see more examples. But to answer your specific question, no, to limit the number of database records shown--to implement pagination, you'd still use a while loop, but limit your query to only returning X records from the database. 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...