Jump to content
Larry Ullman's Book Forums

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
 
 
Link to comment
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.

Link to comment
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. 

Link to comment
Share on other sites

  • 2 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

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...
 Share

×
×
  • Create New...