when to use while loop rather than 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);
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.