Zakiyyah's explanations are spot on. Here are some examples in C++, but the concepts are the same for most languages.
Proper use of a While Loop
Here we are taking user input and insisting the user give us a positive number:
int num;
cout << "What is your favorite positive integer? ";
cin >> num
while(num <= 0)
{
cout << "What is your favorite positive integer? ";
cin >> num;
}
cout << "My favorite number is " << num << ", too!" << endl;
This can be written with a for loop, but it just looks ugly. The reason we use a while loop is because we don't know how many times the user will give us the wrong kind of number.
int num;
cout << "What is your favorite positive integer? ";
cin >> num
for(; num <=0 ; )
{
cout << "What is your favorite positive integer? ";
cin >> num;
}
Notice how I had to leave the initialization and incrementation parts blank -- I have no need for them! Why? Because I don't know how many times they will give me an incorrect value!
Proper Use of a For Loop
If I know how many times I want to loop, I use a for loop. For example, here I will print out the contents of a vector of ints.
vector<int> myVec;
myVec.push_back(1);
myVec.push_back(2);
myVec.push_back(3);
//The myVec variable is a vector containing 1, 2 and 3
for(int i = 0; i < myVec.size(); ++i)
{
cout << "The number is: " << myVec[i] << endl;
}
I knew that exactly how many iterations I needed. I needed one for each element in the vector. I could do this as a while loop, but there are traps to doing so.
/* Initialize the vector same as above */
int i = 0;
while(i < myVec.size() )
{
cout << "The number is: " << myVec[i] << endl;
++i;
}
When using while loops in this fashion, one place you could make an error is forgetting to increment the loop counter (in this case the variable i). Doing so would give you an infinite loop and you wouldn't know it until run time. The for loop is better because it is designed with an incrementation portion so you won't forget it.