when to use while loop rather than for loop

Viewed 51216

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

14 Answers

Use a FOR loop when you know the number of times you want to loop. The technical term for that is the number of iterations. How do you know the number of iterations? You know the start, stop and step. If you know those three pieces of information, you should use a FOR loop because it's the right tool for the job.
Use a DO loop when you don't know the number of iterations. If you don't know the start, stop, step or some combination of those then you need to use a DO loop. The expression will be evaluated at the top of the loop. Use a DO WHILE loop if you want to loop at least once. Use just a WHILE loop if you don't want to loop at least once. The expression will be evaluated at the bottom of the loop.

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.

For loops include the notion of counting, which is great. Yet, when you don’t know how many times the code should run, while loops make sense.

Related