I am learning java as well android. Almost everything that we can perform by while loop those things we can do in for loop.
I found a simple condition where using w
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter); // method which use that value of counter do some other task
Hi I repeat your code because it is incorrect. You forget to increase your counter so it will remains on 0
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
counter++;
}
useTheCounter(counter); // method which use that value of counter do some other task
The while loop is generally better when you don't have an iterator (counter usually).
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.
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);
while
loops are much more flexible, while for
loops are much more readable, if that's what you're asking. If you are wondering which one is faster, then look at this experiment I conducted concerning the speed of for
and while
loops.
https://sites.google.com/a/googlesciencefair.com/science-fair-2012-project-96b21c243a17ca64bdad77508f297eca9531a766-1333147438-57/home
while
loops are faster.
For loops include the notion of counting, which is great. Yet, when you don’t know how many times the code should run, while loops make sense.