For Loop vs. While Loop


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: For Loop vs. While Loop

  1. #1
    Join Date
    Mar 2006
    Posts
    37

    For Loop vs. While Loop

    Hey Everyone, I was googling on which is better, for or while. I have read some interesting arguments on both sides. However this was in a php forum. I did like one persons response and that was Each had it's on use. If you knew how many times you needed to loop then use a for loop. If you want to loop until a certain condition was met then use a while loop.

    I just want everyone's opinioins. I am open to listen to anyone and I am not trying to start a huge flame thread. I just one true facts.

  2. #2
    Join Date
    May 2005
    Posts
    75
    I find myself using for loops more often but they're really very similar. I suppose it depends on the condition you're working with. I use while loops when the condition that needs to be met is determined by a boolean object.

  3. #3
    Join Date
    Apr 2006
    Posts
    21
    Yep, you hit it in the nail, javatier. For loops are used when you know how many times you need to loop. While loops are used to loop until an event occurs.
    Also, note that whatever you can do with a for loop, you can do it with a while loop (just add a variable that increments in the while loop and uses it to break out of the loop when the variable reaches a certain value). However, the reverse is not true (whatever you can do with a while do can not be done in a for loop).

    So in a sense, the while loop is more powerful than the for loop

  4. #4
    Join Date
    Oct 2005
    Posts
    107
    Code:
    for(;;){
    if(conditionMet) break;
    //code
    }
    
    while(!conditionMet){
    //code
    }
    Show me something you can do in a while loop that you can't do in a for loop.

  5. #5
    Join Date
    Mar 2006
    Posts
    37
    I do find myself using While Loops alot more. The reason being is that I do not know when my programs will stop. But can you also use a for loop to evaluate a true or false expression. IE
    Code:
    for(;answer != true;)
    {
      // Some Code 
    }
    or would that code violate any rules.

    I am Starting to really lean towards which ever one works for you then use it.

    Please keep the opinions coming. I am actually Learning alot. Just form what everyone said I have learned when to use them and other ways to use these loops.

    Thanks to everyone so far for your valuable input.

  6. #6
    Join Date
    Feb 2006
    Location
    Cologne - Germany
    Posts
    271
    well, while, do and for loops can do the same work. it's just a question of readability.
    try to use for loops when iterating through a defined range, so you can fill in the three optional arguments of the for loop.
    use while, if you have a single condition with no iteration (the i++ part of for).
    at all: make your code readable, since something like
    for(;{
    if(conditionMet) break;
    //code
    }
    is not well readable.

  7. #7
    Join Date
    Apr 2006
    Posts
    2
    Quote Originally Posted by javatier
    Hey Everyone, I was googling on which is better, for or while. I have read some interesting arguments on both sides. However this was in a php forum. I did like one persons response and that was Each had it's on use. If you knew how many times you needed to loop then use a for loop. If you want to loop until a certain condition was met then use a while loop.

    I just want everyone's opinioins. I am open to listen to anyone and I am not trying to start a huge flame thread. I just one true facts.

    Well For loop is used when you know the number of iterations you have to make, i mean when you know how many times to execute a loop. WHILE is used when you are not sure about the iterations but you know what the condition is and then you can loop that till the condition is met.

    There is another loop too which is DO WHILE, here atleast the loop is executed once and then if the condition is met it will execute further otherwise the loop will exit.

    well i am new to JAVA. but the above thing is based on other programming languages concept..

    Regards,

  8. #8
    Join Date
    Mar 2006
    Posts
    37
    Originally Posted by erpriyankajain
    Well For loop is used when you know the number of iterations you have to make, i mean when you know how many times to execute a loop. WHILE is used when you are not sure about the iterations but you know what the condition is and then you can loop that till the condition is met.

    There is another loop too which is DO WHILE, here atleast the loop is executed once and then if the condition is met it will execute further otherwise the loop will exit.

    well i am new to JAVA. but the above thing is based on other programming languages concept..

    Regards,
    I could not agree more with you erpriyankajain. After reading from one of my Java Books I have made up my mind that each one does have a purpose.

  9. #9
    Join Date
    Mar 2005
    Location
    UK, London
    Posts
    150
    As mentioned quite a few time, each type of loop has its purpose. I just want to bring to your attention that a for loop can do what a while loop does.

    Example.

    Code:
    public class forLoop{
             static String strInput;
             static int intInput;
             
             public static void main (String args[]){
             for (int i=0; i<1;i++){
                      
                      strInput = JOptionPane.showInputDialog(null,"Enter a number between 1 and 10");
                      intInput = Integer.parseInt(strInput);
                               
                                        if ((intInput <0) || (intInput>10)){
                                        i--;
                                        }
                      }
             }
    }
    The above code example, asks the user to enter a number between 0 and 10. If the input is not between this range, the loop will continue for ever until a valid input is entered. As you can see although the for loop acts like a while loop, the code is slighly unreadable. So its best to use a type of loop where it is best suited. In a nutshell, each loop was designed for a readon and it is best to use them for those reasons.

  10. #10
    Join Date
    Oct 2005
    Posts
    107
    whenever i write a server i find my self always using

    Code:
    for(;;){
    
    }
    
    //instead of
    while(true){
    
    }
    But yeah they each have their purpose.

    Do they have that for loop for iterators in 1.5? So I don't have to write code like this...

    Code:
    for(Iterator iter = list.iterator(); iter.hasNext();){
    
    }
    //or
    Iterator iter = list.iterator;
    while(iter.hasNext()){
    
    }
    
    
    //is this in 1.5 ?
    for each(....){
    
    }
    I've sadly taken a job using VB .NET which might I add has the weakest compiler. So I'm not up to date on the new 1.5 constructs.
    Last edited by Joe Beam; 04-22-2006 at 08:49 AM.

  11. #11
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Actually, the extended for loop does not explicity use an iterator. You'll see a code sample like this in the following reference from the Java Guide:

    Code:
    for( Suit mySuit : suits )
       for( Rank myRank : ranks ) 
           sortedDeck.add(new Card(mySuit, myRank));
    there is an iterator created behind the scenes, starting at the first element and going to the end.

    http://java.sun.com/j2se/1.5.0/docs/...e/foreach.html

    This is specific for those many "do this with every element of this collection" tasks. You can't stop it to insert or delete or other such tasks.

  12. #12
    Join Date
    Oct 2005
    Posts
    107
    That looks so much cleaner than this clunky vb .net equvalent
    Code:
    for each item as Object in MyList
    
    next

  13. #13
    Join Date
    Mar 2008
    Posts
    1
    I agree with most of these posts. I don't think they are entirely accurate though. I agree with sentinel controlled repetition vs counter controlled (while vs for) But one instance a while loop perhaps would not work correctly vs a for loop is if you had say a continue statement before your counter was incremented. For example: // Count to ten

    public class Count
    {
    public static void main(String [] args)
    {
    int counter = 1;

    while (counter <= 10)
    {
    if (counter == 5)
    continue;
    counter++;
    }
    }
    }

    I think in this example perhaps a for loop vs a while loop could not be used interchangeably..

    Just a though..
    thanks

  14. #14
    Join Date
    Apr 2010
    Posts
    1

    Cool Great info

    I had actually wondered the real difference for a long time. Not sure why I never looked it up.

    I may be wrong, but working with Flash Actionscript I get the feeling that another difference between a for and a while loop is that when you run a while loop it seems to completely lock up the system until the loop is finshed. With a for loop I don't seem to notice this. Is it because Flash can only run 1 thread at once? Or am I just crazy..


    10 REM PLUCK EYES OUT NOW
    20 FOR A = 1 TO 10
    30 ? "ITERATION #";A
    40 NEXT A

  15. #15
    Join Date
    May 2004
    Posts
    40
    Just to stir the pot:

    Code:
    for( ;;; )
    is usually read as forever. That's why it is often used in place of a while loop by some developers.

Similar Threads

  1. Replies: 2
    Last Post: 03-16-2006, 06:39 PM
  2. For Loop Help
    By naazrael in forum Java
    Replies: 2
    Last Post: 12-14-2005, 10:22 AM
  3. Replies: 2
    Last Post: 08-25-2005, 02:00 PM
  4. How to loop through rows in Datalist control?
    By Acceris in forum ASP.NET
    Replies: 0
    Last Post: 06-30-2005, 02:31 PM
  5. Problem with a loop
    By salvinger in forum VB Classic
    Replies: 0
    Last Post: 05-07-2005, 01:38 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center