when to use while loop rather than for loop

One main difference is while loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can use for loop.


A for loop is just a special kind of while loop, which happens to deal with incrementing a variable. You can emulate a for loop with a while loop in any language. It's just syntactic sugar (except python where for is actually foreach). So no, there is no specific situation where one is better than the other (although for readability reasons you should prefer a for loop when you're doing simple incremental loops since most people can easily tell what's going on).

For can behave like while:

while(true)
{
}

for(;;)
{
}

And while can behave like for:

int x = 0;
while(x < 10)
{
    x++;
}

for(x = 0; x < 10; x++)
{
}

In your case, yes you could re-write it as a for loop like this:

int counter; // need to declare it here so useTheCounter can see it

for(counter = 0; counter < 10 && !some_condition; )
{
    //do some task
}

useTheCounter(counter);

for and while are equivalent, just a different syntax for the same thing.


You can transform this

while( condition ) {
   statement;
}

to this:

for( ; condition ; ) {
    statement;
}

The other way:

for( init; condition; update) {
    statement;
}

is equivalent to this:

init;
while(condition) {
    statement;
    update;
}

So, just use which looks better, or is easier to speak.


Remember,

Everything done with a for loop can be done with a while loop, BUT not all while loops can be implemented with a for loop.

WHILE :

While-loops are used when the exiting condition has nothing to do with the number of loops or a control variable

FOR :

for-loops are just a short-cut way for writing a while loop, while an initialization statement, control statement (when to stop), and a iteration statement (what to do with the controlling factor after each iteration).

For e.g,

Basically for loops are just short hand for while loops, any for loop can be converted from:

for([initialize]; [control statement]; [iteration]) {
   // ...
  }

and

[initialize]; 
while([control statement]) { 
   //Do something [iteration];
   } 

are same.


Use a FOR loop when you know the number of times you want to loop. The technical term for that is the number of iterations. How do you know the number of iterations? You know the start, stop and step. If you know those three pieces of information, you should use a FOR loop because it's the right tool for the job.
Use a DO loop when you don't know the number of iterations. If you don't know the start, stop, step or some combination of those then you need to use a DO loop. The expression will be evaluated at the top of the loop. Use a DO WHILE loop if you want to loop at least once. Use just a WHILE loop if you don't want to loop at least once. The expression will be evaluated at the bottom of the loop.