when to use while loop rather than for loop

2020-02-01 02:32发布

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 while loop is better than for loop

if i have to use the value of counter in my program then i think while loop is better than for loop

Using while loop

int counter = 0;
while (counter < 10) {
    //do some task
    if(some condition){
        break;
    }
}
useTheCounter(counter); // method which use that value of counter do some other task

In this case I found while loop is better than for loop because if i want to achieve the same in for loop i have to assign the value of counter to another variable.

But is there any specific situation when while loop is better than for loop

13条回答
唯我独甜
2楼-- · 2020-02-01 02:54

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.

查看更多
男人必须洒脱
3楼-- · 2020-02-01 02:55

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-01 02:55

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.

查看更多
家丑人穷心不美
5楼-- · 2020-02-01 02:58

The while loop is generally better when you don't have an iterator (counter usually).

查看更多
够拽才男人
6楼-- · 2020-02-01 02:58

while loops are much more flexible, while for loops are much more readable, if that's what you're asking. If you are wondering which one is faster, then look at this experiment I conducted concerning the speed of for and while loops.

https://sites.google.com/a/googlesciencefair.com/science-fair-2012-project-96b21c243a17ca64bdad77508f297eca9531a766-1333147438-57/home

while loops are faster.

查看更多
Explosion°爆炸
7楼-- · 2020-02-01 03:01

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.

查看更多
登录 后发表回答