when to use while loop rather than for loop

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

    A for loop is just a special kind of while loop, which happens to deal with incrementing a variable. You can emulate a for loop with a while loop in any language. It's just syntactic sugar (except python where for is actually foreach). So no, there is no specific situation where one is better than the other (although for readability reasons you should prefer a for loop when you're doing simple incremental loops since most people can easily tell what's going on).

    For can behave like while:

    while(true)
    {
    }
    
    for(;;)
    {
    }
    

    And while can behave like for:

    int x = 0;
    while(x < 10)
    {
        x++;
    }
    
    for(x = 0; x < 10; x++)
    {
    }
    

    In your case, yes you could re-write it as a for loop like this:

    int counter; // need to declare it here so useTheCounter can see it
    
    for(counter = 0; counter < 10 && !some_condition; )
    {
        //do some task
    }
    
    useTheCounter(counter);
    

提交回复
热议问题