This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

While loop and for loop

 
rajeshchowdary rajesh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the need of creating two loops while and for? what is the difference between the two?one is sufficient to do the functionality then wht is the need of other?(interview question faced by me)
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really, of course, there are three loop constructs in Java. There's "for() { }", "while() { }" and "do { } while()".

It is true that any loop could be implemented with any of the types of loop construct. However, having them both allows code to be clearer and more concise. That is, once the developer is sufficiently experienced to allow them to choose the best loop construct for each circumstance.

In general, "for" is for looping a known number of times, "while" is for looping until a condition is met, and "do while" is shunned.
 
bksella sella
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to give you some more information, the FOR and WHILE loops can be skipped entirely, if the condition specified is not met, whereas "DO WHILE" loop will be executed at least once before the given condition is checked.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The quick answer is that the readability of your code will be better if you use the type of loop that most represents what you are trying to do. (The long answer would show examples of all of those.)

Also note, the new version of java has a second for loop. The original "for (; {}" and the new "for ( {}". The new provides a shorthand for iterating over collections and arrays. See yesterday's post on the topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic