when to use while loop rather than for loop
Asked Answered
B

15

13

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

Broadway answered 15/7, 2011 at 17:0 Comment(1)
I'd just do useTheCounter(10)Tracietracing
D
24

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.

Dunseath answered 15/7, 2011 at 17:4 Comment(2)
Can you give a example for your answer?Tenorio
Typically when reading a file line-by-line from a buffer you would use a while loop (as you don't know when the End-of-File marker will appear)Bibliotherapy
S
15

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);
Schwinn answered 15/7, 2011 at 17:3 Comment(2)
actually the counter var is not accessible outside the for (unless you declare it outside it ofcourse)Zurn
while and for are not exactly the same when using increment - if you also need to use continue. With the while the variable will not increment (without additional effort), but with for it will.Slop
H
8

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.

Haig answered 15/7, 2011 at 17:11 Comment(0)
D
4

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.

Donniedonnish answered 9/2, 2019 at 16:36 Comment(0)
E
3

Remember,

Everything done with a for loop can be done with a while loop, BUT not all while loops can be implemented with a for loop.

WHILE :

While-loops are used when the exiting condition has nothing to do with the number of loops or a control variable

FOR :

for-loops are just a short-cut way for writing a while loop, while an initialization statement, control statement (when to stop), and a iteration statement (what to do with the controlling factor after each iteration).

For e.g,

Basically for loops are just short hand for while loops, any for loop can be converted from:

for([initialize]; [control statement]; [iteration]) {
   // ...
  }

and

[initialize]; 
while([control statement]) { 
   //Do something [iteration];
   } 

are same.

Evocation answered 15/7, 2011 at 17:8 Comment(1)
Omit the initialize and the iteration, the for loop will act exactly like a while loopHamitosemitic
M
2

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

Monkeypot answered 15/7, 2011 at 17:2 Comment(7)
for can be infinite: for(;;)Schwinn
for can be infinite too: for (i = 1; i == i - 1; i++) { ... }Tracietracing
Using for if you want to touch all elements in a collection and while if you would want to break early is quite sensible.Maki
@K4emic: you can break out of a for loop in the same way you'd break out of a while loop. There's no difference.Schwinn
@Chris Of course, did I write something that indicated that you could not? I merely stated what I see as a reasonable way to differentiate between which way to loop through collections.Maki
but both can be infinite if you don't break out either by meeting a condition or jumping out.Ulster
they do same thing....the only diff is that for can make ur code shorter most times, but you can archive same thing with both. you can use whichever that best suits your situation.Ulster
M
2

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

Mammy answered 15/7, 2011 at 17:3 Comment(0)
M
1

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.

Malinin answered 15/7, 2011 at 17:4 Comment(0)
M
1

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.

Miscellany answered 15/7, 2011 at 17:6 Comment(0)
T
1

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.

Tracietracing answered 15/7, 2011 at 17:7 Comment(0)
I
1
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

Hi I repeat your code because it is incorrect. You forget to increase your counter so it will remains on 0

int counter = 0;
while (counter < 10) {
  //do some task
  if(some condition){
      break;
  }
  counter++;
}
useTheCounter(counter); // method which use that value of counter do some other task
Intersex answered 5/7, 2014 at 10:49 Comment(0)
F
1

Usually while loops are used for I/O, like waiting for input from the user or waiting for data from the web, which are situations where the code has no capability of knowing how many times it should do something (like how many times the program should it should check if it's received user input yet).

Fid answered 15/3, 2023 at 22:30 Comment(0)
A
0

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.

Alfi answered 1/4, 2012 at 14:35 Comment(0)
T
0

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.

Tract answered 22/1, 2020 at 13:20 Comment(0)
G
0

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.

Gastrulation answered 30/6, 2020 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.