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?
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?
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.
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
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.
Some examples.
Exercise 1: Display the numbers from 0-9.
When a programmer is writing that program, he/she knows exactly how many times the loop needs to be repeated to accomplish the task.Code:#include <iostream> using namespace std; int main() { for(int i = 0; i <= 9; i++) { cout<<i<<endl; } return 0; }
Exercise 2: Ask the user to input a number between 0-9, and then display the numbers between the input number and 9.
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.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; }
Last edited by 7stud; 04-23-2005 at 06:35 PM.
Well on your second example 7stud I'd still use a for loop.
or evenCode:for(;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.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 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;
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
Two can play that game. Wouldn't this work as well?Originally Posted by Thantos
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:
...a for-loop used for an indeterminate number of loops.Code:cout<<"enter a number between 0-9"<<endl; cin>>input; for(;;) { if(++input > 9) break; cout<<input<<endl; }
nor this one:
...once again a for-loop used for an indeterminate number of loops.Code:cout<<"enter a number between 0-9"<<endl; cin>>input; for(int i=input+1; i<= 9; cout<<i++<<endl) ;
nor this one
...a while loop used for a predetermined number of loops.Code://display numbers 0-9: int i = 0; while(i <= 9) { cout<<i++<<endl; }
Does that mean a general 'rule' isn't a good starting point?
Last edited by 7stud; 04-24-2005 at 05:47 AM.
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++.
...err..well Salem posted it first. I just posted some examples, so the poster could see what the others were talking about.So I'd say 7stud's original answer is probably the best advice to follow if youre just learning c++.
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:
for another: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
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.Code:ifstream in("bob.txt"); while ( in ) // Do something to read the file
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.