when to use while loop rather than for loop

前端 未结 14 947
清酒与你
清酒与你 2020-12-06 02:59

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

相关标签:
14条回答
  • 2020-12-06 03:28

    What ever you can write in for loop can be converted to while loop. Benefits of using for loop are

    1. The syntax allows you to start a counter, set the condition to exit loop, then auto increment.

    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.

    0 讨论(0)
  • 2020-12-06 03:33

    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.

    0 讨论(0)
提交回复
热议问题