[ACCEPTED]-Test loops at the top or bottom? (while vs. do while)-do-while

Accepted answer
Score: 78

I always follow the rule that if it should 5 run zero or more times, test at the beginning, if 4 it must run once or more, test at the end. I 3 do not see any logical reason to use the 2 code you listed in your example. It only 1 adds complexity.

Score: 58

Use while loops when you want to test a 7 condition before the first iteration of 6 the loop.

Use do-while loops when you want 5 to test a condition after running the first 4 iteration of the loop.

For example, if you 3 find yourself doing something like either 2 of these snippets:

func();
while (condition) {
   func();
}

//or:

while (true){
    func();
    if (!condition) break;
}

You should rewrite it 1 as:

do{
    func();
} while(condition);
Score: 20

Difference is that the do loop executes 4 "do something" once and then checks the 3 condition to see if it should repeat the 2 "do something" while the while loop checks 1 the condition before doing anything

Score: 17

Does avoiding do/while really help make my code 5 more readable?

No.

If it makes more sense 4 to use a do/while loop, then do so. If you need 3 to execute the body of a loop once before 2 testing the condition, then a do/while loop is 1 probably the most straightforward implementation.

Score: 12

First one may not execute at all if condition 2 is false. Other one will execute at least 1 once, then check the conidition.

Score: 7

For the sake of readability it seems sensible 4 to test at the top. The fact it is a loop 3 is important; the person reading the code 2 should be aware of the loop conditions before 1 trying to comprehend the body of the loop.

Score: 6

Here's a good real-world example I came 14 across recently. Suppose you have a number 13 of processing tasks (like processing elements 12 in an array) and you wish to split the work 11 between one thread per CPU core present. There 10 must be at least one core to be running 9 the current code! So you can use a do... while something 8 like:

do {
    get_tasks_for_core();
    launch_thread();
} while (cores_remaining());

It's almost negligable, but it might 7 be worth considering the performance benefit: it 6 could equally be written as a standard while loop, but 5 that would always make an unnecessary initial 4 comparison that would always evaluate true - and 3 on single-core, the do-while condition branches 2 more predictably (always false, versus alternating 1 true/false for a standard while).

Score: 5

Yaa..its true.. do while will run atleast 2 one time. Thats the only difference. Nothing 1 else to debate on this

Score: 4

The first tests the condition before performing 3 so it's possible your code won't ever enter 2 the code underneath. The second will perform 1 the code within before testing the condition.

Score: 4

The while loop will check "condition" first; if 3 it's false, it will never "do something." But 2 the do...while loop will "do something" first, then 1 check "condition".

Score: 4

Yes, just like using for instead of while, or 4 foreach instead of for improves readability. That 3 said some circumstances need do while and 2 I agree you would be silly to force those 1 situations into a while loop.

Score: 4

It's more helpful to think in terms of common 7 usage. The vast majority of while loops 6 work quite naturally with while, even if they 5 could be made to work with do...while, so basically 4 you should use it when the difference doesn't 3 matter. I would thus use do...while for the rare scenarios 2 where it provides a noticeable improvement 1 in readability.

Score: 3

The use cases are different for the two. This 6 isn't a "best practices" question.

If you 5 want a loop to execute based on the condition 4 exclusively than use for or while

If you want to 3 do something once regardless of the the 2 condition and then continue doing it based 1 the condition evaluation. do..while

Score: 3

For anyone who can't think of a reason to 3 have a one-or-more times loop:

try {
    someOperation();
} catch (Exception e) {
    do {
        if (e instanceof ExceptionIHandleInAWierdWay) {
            HandleWierdException((ExceptionIHandleInAWierdWay)e);
        }
    } while ((e = e.getInnerException())!= null);
}

The same could 2 be used for any sort of hierarchical structure.

in 1 class Node:

public Node findSelfOrParentWithText(string text) {
    Node node = this;
    do {
        if(node.containsText(text)) {
            break;
        }
    } while((node = node.getParent()) != null);
    return node;
}
Score: 3

A while() checks the condition before each execution 9 of the loop body and a do...while() checks the condition 8 after each execution of the loop body.

Thus, **do...while()**s 7 will always execute the loop body at least 6 once.

Functionally, a while() is equivalent 5 to

startOfLoop:
    if (!condition)
        goto endOfLoop;

    //loop body goes here

    goto startOfLoop;
endOfLoop:

and a do...while() is equivalent to

startOfLoop:

    //loop body

    //goes here
    if (condition)
        goto startOfLoop;

Note 4 that the implementation is probably more 3 efficient than this. However, a do...while() does 2 involve one less comparison than a while() so 1 it is slightly faster. Use a do...while() if:

  • you know that the condition will always be true the first time around, or
  • you want the loop to execute once even if the condition is false to begin with.
Score: 3

Here is the translation:

do { y; } while(x); 

Same as

{ y; } while(x) { y; }

Note the 10 extra set of braces are for the case you 9 have variable definitions in y. The scope 8 of those must be kept local like in the 7 do-loop case. So, a do-while loop just executes 6 its body at least once. Apart from that, the 5 two loops are identical. So if we apply 4 this rule to your code

do {
    // do something
} while (condition is true);

The corresponding 3 while loop for your do-loop looks like

{
    // do something
}
while (condition is true) {
    // do something
}

Yes, you 2 see the corresponding while for your do 1 loop differs from your while :)

Score: 3

As noted by Piemasons, the difference is 17 whether the loop executes once before doing 16 the test, or if the test is done first so 15 that the body of the loop might never execute.

The 14 key question is which makes sense for your 13 application.

To take two simple examples:

  1. Say 12 you're looping through the elements of an 11 array. If the array has no elements, you 10 don't want to process number one of zero. So 9 you should use WHILE.

  2. You want to display 8 a message, accept a response, and if the 7 response is invalid, ask again until you 6 get a valid response. So you always want 5 to ask once. You can't test if the response 4 is valid until you get a response, so you 3 have to go through the body of the loop 2 once before you can test the condition. You 1 should use DO/WHILE.

Score: 3

I tend to prefer do-while loops, myself. If 10 the condition will always be true at the start 9 of the loop, I prefer to test it at the 8 end. To my eye, the whole point of testing 7 conditions (other than assertions) is that 6 one doesn't know the result of the test. If 5 I see a while loop with the condition test 4 at the top, my inclination is to consider 3 the case that the loop executes zero times. If 2 that can never happen, why not code in a 1 way that clearly shows that?

Score: 2

It's actually meant for a different things. In 8 C, you can use do - while construct to achieve both 7 scenario (runs at least once and runs while 6 true). But PASCAL has repeat - until and while for each scenario, and 5 if I remember correctly, ADA has another 4 construct that lets you quit in the middle, but 3 of course that's not what you're asking. My 2 answer to your question : I like my loop 1 with testing on top.

Score: 2

Both conventions are correct if you know 8 how to write the code correctly :)

Usually 7 the use of second convention ( do {} while() ) is meant 6 to avoid have a duplicated statement outside 5 the loop. Consider the following (over simplified) example:

a++;
while (a < n) {
  a++;
}

can 4 be written more concisely using

do {
  a++;
} while (a < n)

Of course, this 3 particular example can be written in an 2 even more concise way as (assuming C syntax)

while (++a < n) {}

But 1 I think you can see the point here.

Score: 2
while( someConditionMayBeFalse ){

// this will never run...

}


// then the alternative

do{

// this will run once even if the condition is false

while( someConditionMayBeFalse );

The difference is obvious and allows you 5 to have code run and then evaluate the result 4 to see if you have to "Do it again" and 3 the other method of while allows you to 2 have a block of script ignored if the conditional 1 is not met.

Score: 1

I write mine pretty much exclusively testing 4 at the top. It's less code, so for me at 3 least, it's less potential to screw something 2 up (e.g., copy-pasting the condition makes 1 two places you always have to update it)

Score: 1

It really depends there are situations when 8 you want to test at the top, others when 7 you want to test at the bottom, and still 6 others when you want to test in the middle.

However 5 the example given seems absurd. If you 4 are going to test at the top, don't use 3 an if statement and test at the bottom, just 2 use a while statement, that's what it is 1 made for.

Score: 1

You should first think of the test as part 8 of the loop code. If the test logically 7 belongs at the start of the loop processing, then 6 it's a top-of-the-loop test. If the test 5 logically belongs at the end of the loop 4 (i.e. it decides if the loop should continue 3 to run), then it's probably a bottom-of-the-loop 2 test.

You will have to do something fancy 1 if the test logically belongs in them middle. :-)

Score: 1

I guess some people test at the bottom because 2 you could save one or a few machine cycles 1 by doing that 30 years ago.

Score: 1

To write code that is correct, one basically 27 needs to perform a mental, perhaps informal 26 proof of correctness.

To prove a loop correct, the 25 standard way is to choose a loop invariant, and 24 an induction proof. But skip the complicated 23 words: what you do, informally, is figure 22 out something that is true of each iteration 21 of the loop, and that when the loop is done, what 20 you wanted accomplished is now true. The 19 loop invariant is false at the end, for 18 the loop to terminate.

If the loop conditions 17 map fairly easily to the invariant, and 16 the invariant is at the top of the loop, and 15 one infers that the invariant is true at 14 the next iteration of the loop by working 13 through the code of the loop, then it is 12 easy to figure out that the loop is correct.

However, if 11 the invariant is at the bottom of the loop, then 10 unless you have an assertion just prior 9 to the loop (a good practice) then it becomes 8 more difficult because you have to essentially 7 infer what that invariant should be, and 6 that any code that ran before the loop makes 5 the loop invariant true (since there is 4 no loop precondition, code will execute 3 in the loop). It just becomes that more 2 difficult to prove correct, even if it is 1 an informal in-your-head proof.

Score: 1

This isn't really an answer but a reiteration 13 of something one of my lecturers said and 12 it interested me at the time.

The two types 11 of loop while..do and do..while are actually 10 instances of a third more generic loop, which 9 has the test somewhere in the middle.

begin loop
  <Code block A>
  loop condition
  <Code block B>
end loop

Code 8 block A is executed at least once and B 7 is executed zero or more times, but isn't 6 run on the very last (failing) iteration. a 5 while loop is when code block a is empty 4 and a do..while is when code block b is 3 empty. But if you're writing a compiler, you 2 might be interested in generalizing both 1 cases to a loop like this.

Score: 0

In a typical Discrete Structures class in 12 computer science, it's an easy proof that 11 there is an equivalence mapping between 10 the two.

Stylistically, I prefer while (easy-expr) { } when 9 easy-expr is known up front and ready to 8 go, and the loop doesn't have a lot of repeated 7 overhead/initialization. I prefer do { } while 6 (somewhat-less-easy-expr); when there is 5 more repeated overhead and the condition 4 may not be quite so simple to set up ahead 3 of time. If I write an infinite loop, I 2 always use while (true) { }. I can't explain 1 why, but I just don't like writing for (;;) { }.

Score: 0

I would say it is bad practice to write 16 if..do..while loops, for the simple reason 15 that this increases the size of the code 14 and causes code duplications. Code duplications 13 are error prone and should be avoided, as 12 any change to one part must be performed 11 on the duplicate as well, which isn't always 10 the case. Also, bigger code means a harder 9 time on the cpu cache. Finally, it handles 8 null cases, and solves head aches.

Only when 7 the first loop is fundamentally different 6 should one use do..while, say, if the code 5 that makes you pass the loop condition (like 4 initialization) is performed in the loop. Otherwise, if 3 it certain that loop will never fall on 2 the first iteration, then yes, a do..while 1 is appropriate.

Score: 0

From my limited knowledge of code generation 8 I think it may be a good idea to write bottom 7 test loops since they enable the compiler 6 to perform loop optimizations better. For 5 bottom test loops it is guaranteed that 4 the loop executes at least once. This means 3 loop invariant code "dominates" the exit 2 node. And thus can be safely moved just 1 before the loop starts.

Score: 0

Generally, it depends on how you structure 4 your code. And as someone already answered, some 3 algorithms need at least one iteration performed. So, to 2 escape additional iteration-count or at-least-one-interation-occured 1 flag - you employ do/while.

More Related questions