Thread: "for" loop or "while" loop?

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    60

    "for" loop or "while" loop?

    I'm just learning C++. What is the difference between these two loops and can anyone show an example of what loop to use when?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    They're pretty much the same.
    Use a for loop if you know how many iterations you have - say indexing an array
    Use a while loop if you don't know, say reading lines from a file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Salem's answer is a good rule of thumb for beginners.

    I'd say use a for loop if you have need of what it provides: an action that needs to be done once at the start of the looping, a condition on which the continued looping depends and an action that needs to be done between each iteration that can be described as "fetch the data for the next iteration".
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Registered User
    Join Date
    Aug 2004
    Location
    San Diego, CA
    Posts
    313
    I think of it this way:

    A while loop is good if you have an ending condition but no given starting position. A for loop is good if you have a known starting and ending position.

    Example:

    Count to 10. Here, I would use a while loop, because I don't know where I start from. That's given to me somewhere else. I just know that I have to get what I got up (or down) to 10.

    Count to 10, starting at 1. Here, I would use a for loop because I know the starting and ending conditions.

    Just my 2 cp.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Some examples.

    Exercise 1: Display the numbers from 0-9.
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	for(int i = 0; i <= 9; i++)
    	{
    		cout<<i<<endl;
    	}
    
    	return 0;
    }
    When a programmer is writing that program, he/she knows exactly how many times the loop needs to be repeated to accomplish the task.

    Exercise 2: Ask the user to input a number between 0-9, and then display the numbers between the input number and 9.
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
    	//Get a number from the user:
    	int input;
    	cout<<"Enter a number between 0-9: ";
    	cin>>input;
    
    	while(input<=9)
    	{
    		cout<<input<<endl;
    		input = input + 1;
    	}
    
    	return 0;
    }
    Generally, you use a for loop when you know exactly how many times you want to loop. A while loop is used when you don't know how many times your program will loop at the time you are writing the program. In the while loop above, the programmer has no idea how many times the program will need to loop since it depends on what the user inputs.
    Last edited by 7stud; 04-23-2005 at 06:35 PM.

  6. #6
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Well on your second example 7stud I'd still use a for loop.
    Code:
    for(;input <= 9; input++)
      cout<<input<<endl;
    or even
    Code:
            int input;
            cout<<"Input a number between 0 and 9: ";
            for(cin>>input; input >= 0 && input <= 9; input++)
                    cout<<input<<endl;
    I (generally) use for loops when I have a variable that has the same small action preformed upon it every iteration and that variable directly affects the condition.

    I (generally) use while loops when I have a variable that does not have the same action preformed upon it iteration or when such variable does not directly contribute to the condition.

    Code:
    int i;
    while( (i=rand()) != 5 )
      cout<<i<<endl;

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The condition "when you know exactly how many times to loop" also prevents the standard C-string iteration loop:
    for(char *p = str; *p; ++p)
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Quote Originally Posted by Thantos
    I (generally) use while loops when I have a variable that does not have the same action preformed upon it iteration or when such variable does not directly contribute to the condition.
    Code:
    int i;
    while( (i=rand()) != 5 )
      cout<<i<<endl;
    Two can play that game. Wouldn't this work as well?
    Code:
    int i = rand();
    for(;i!=5; i=rand())
    	cout<<i<<endl;


    The predeterminable-number-of-loops-calls-for-a-for-loop "rule" also doesn't account for this construct:
    Code:
    cout<<"enter a number between 0-9"<<endl;
    cin>>input;
    
    for(;;)
    {
            if(++input > 9) break;
    	cout<<input<<endl;
    }
    ...a for-loop used for an indeterminate number of loops.

    nor this one:
    Code:
    cout<<"enter a number between 0-9"<<endl;
    cin>>input;
    
    for(int i=input+1; i<= 9; cout<<i++<<endl)
    ;
    ...once again a for-loop used for an indeterminate number of loops.

    nor this one
    Code:
    //display numbers 0-9:
    
    int i = 0;
    while(i <= 9)
    {
    	cout<<i++<<endl;
    }
    ...a while loop used for a predetermined number of loops.

    Does that mean a general 'rule' isn't a good starting point?
    Last edited by 7stud; 04-24-2005 at 05:47 AM.

  9. #9
    Registered User
    Join Date
    Apr 2005
    Posts
    22
    I guess that whenever you have a for loop you could do the same thing with a while loop and vice versa. But for a beginner, using a for loop when you have a predeterminate number of steps to perform and using a while loop when you're checking whether some condition is satisfied or not works fine. Typically i use a for loop for iterating over an array of some kind and a while loop for most other situations.
    So I'd say 7stud's original answer is probably the best advice to follow if youre just learning c++.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    So I'd say 7stud's original answer is probably the best advice to follow if youre just learning c++.
    ...err..well Salem posted it first. I just posted some examples, so the poster could see what the others were talking about.

  11. #11
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    What I was trying to show 7stud is that in both examples you were still iterating over a known range as my second example of the for loop showed. My example on the while loop wasn't the best.
    Maybe this one (adapted from actual usage in PHP) is better example:
    Code:
    MYSQL_RES *res;
    MYSQL_ROW row;
    res = db_query("SELECT blah blah blah FROM MEH", __FILE__, __LINE__);
    while( row = mysql_fetch_row(res) )
      // Do something with row
    for another:
    Code:
    ifstream in("bob.txt");
    while ( in )
      // Do something to read the file
    And yes any while can be written as a for or do while and any for can be written as a while or do while and any do while can be written as a while or for.

  12. #12
    Resident nerd elnerdo's Avatar
    Join Date
    Apr 2005
    Location
    Northern NJ
    Posts
    51
    Personally, I use while loops with bools only.. Like for a game loop,

    Code:
    bool gamelooprunning;
    gamelooprunning = true;
    
    while (gamelooprunning)
    {
    // all the game loop stuff
    
    if (playerisdead)
    {
    gamelooprunning = false
    }
    }
    nerds unite!

    I'm using windows XP.
    I'm using dev-C++ by bloodshed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 07:19 AM
  4. while loop help
    By bliznags in forum C Programming
    Replies: 5
    Last Post: 03-20-2005, 12:30 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM