when to use while loop rather than for loop

前端 未结 14 945
清酒与你
清酒与你 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:08

    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.

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

    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.

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

    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.

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

    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.

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

    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.

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

    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 ..

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