when to use while loop rather than for loop

前端 未结 14 1036
清酒与你
清酒与你 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.

提交回复
热议问题