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
One thing I feel I should point out is that when you use a for loop, you do not need to assign counter to another variable. For example for(counter=0; counter<10; counter++)
is valid Java code.
As for your question, a for loop is usually better when you want a piece of code to run a certain number of times, and a while loop is better when the condition for the code to keep running is more general, such as having a boolean flag that is only set to true when a certain condition is met in the code block.
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.
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.
You can do something like:
int counter;
for (counter = 0; counter < 10; ) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter);
Anything that a while-loop can do, can also be done in a for-loop, and anything a for-loop can do, can also be done in a while-loop.
No. There's not a specific situation where for
is better than while
.
They do the same thing.
It's up to you choose when apply one of those.
for is finite, in the sense that it will finish looping when it runs out of elements to loop through....
while can be infinite if a condition isn't met or the loop broken
Edit
My mistake ... for
can be infinite ..