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
What ever you can write in for loop can be converted to while loop. Benefits of using for loop are
You can get the same done in while loop also. But all which you can do in while loop is not possible to do in for loop. For example if you have more than one counter and you want any of them to increment based on a condition then while only can use. In for loop at the end of loop the counter increment happens automatically.
Best use
For matrix or single array single directional traversal, for loop is good In case of multiple conditions and multiple counters then while loop is good. if yuo want to traverse an array from both sides based on different conditions then while loop is good.
While loop, there is lot more chance to forget increment counter and ends up into infinite loop, while in for loop syntax will help you to easily set the counter.
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.