5

This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?

e.g.

int count = 0;
do {
   System.out.println("Welcome to Java");
   count++;
} while (count < 10);`

It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).

For something simple like my above example, I would imagine that:

int count = 0; 
while(count < 10) { 
   System.out.println("Welcome to Java"); count++;
}

would be generally considered to have been written in a better writing style.

Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?

(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)

Wouter J
  • 41,455
  • 15
  • 107
  • 112
AlexMTMorgan
  • 67
  • 1
  • 1
  • 10

12 Answers12

6

If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.

do
{ 
   // read data
} while ( /* data is not escape sequence */ );
Enigma
  • 1,699
  • 10
  • 14
5

The while statement continually executes a block of statements while a particular condition is true

while (expression) {
     statement(s)
}

do-while evaluates its expression at the bottom of the loop, and therefore, the statements within the do block are always executed at least once.

do {
     statement(s)
} while (expression);

Now will talk about functional difference,

while-loops consist of a conditional branch instructions such as if_icmpge or if_icmplt and a goto statement. The conditional instruction branches the execution to the instruction immediately after the loop and therefore terminates the loop if the condition is not met. The final instruction in the loop is a goto that branches the byte code back to the beginning of the loop ensuring the byte code keeps looping until the conditional branch is met.

A Do-while-loops are also very similar to for-loops and while-loops except that they do not require the goto instruction as the conditional branch is the last instruction and is be used to loop back to the beginning A do-while loop always runs the loop body at least once - it skips the initial condition check. Since it skips first check, one branch will be less and one less condition to be evaluated.

By using do-while you may gain performance if the expression/condition is complex, since it is ensured to loop atleast once. In that casedo-while could call for performance gain

Very Impressive findings here, http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop

Satheesh Cheveri
  • 3,621
  • 3
  • 27
  • 46
1

Simply, when you want to check condition before and then perform operation while is better option, and if you want to perform operation at least once and then check the condition do-while is better.
As per your question a working example,
1. when I needed to find the field which could be declared in the same class or the super class or the super class of that super class and so on i.e. finding the field located in deep class hierarchy. (A extends B B extends C and so on)

public Field SearchFieldInHierarchy(Object classObj, String fieldName )
{
    Field type = null;
    Class clz = classObj.getClass();
    do
    {
        try
        {
            type = clz.getDeclaredField(fieldName);
            break;
        } catch (NoSuchFieldException e)
        {
            clz = clz.getSuperclass();
        } 
    } while(clz != null || clz != Object.class);        
    return type;
}

2. When reading input stream from Http response

    do 
    {
        bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
        totalBytesRead += bytesRead;
    } while (totalBytesRead < buffer.length && bytesRead != 0);
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
1

The do-while loop is basically an inverted version of the while-loop.

It executes the loop statements unconditionally the first time.

It then evaluates the conditional expression specified before executing the statements again.

int sum = 0;
int i = 0;
do
{
    sum += ids[i];
    i++;
} while (i < 4);

Reference material

DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
0

If the looping condition can only be known after a first step of the loop (when you do not want a condition before you enter the loop). Typically:

do {
  expr = ...;
while (expr);
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
0

You kind of answer the question yourself-when it needs to run at least once, and it makes sense to read it that way.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

do - while loop allows you to ensure that the piece of code is executed at least once before it goes into the iteration.

e.doroskevic
  • 2,129
  • 18
  • 25
0

In a while loop, the condition is tested before it executes code in the loop. In a do while loop, the code is executed before the condition is tested, resulting in the code always being executed at least once. Example:

$value = 5;

while($value > 10){
    echo "Value is greater than 10";
}

The above would never output anything. If we do the same again like this:

$value = 5;

do{
    echo "Value is greater than 10";
}while($value > 10)

It would output Value is greater than 10 because the condition is tested after the loop is executed. After this it would not output anything further.

Scott Helme
  • 4,786
  • 2
  • 23
  • 35
0

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

For example do check this link: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Vignesh
  • 343
  • 2
  • 5
  • 13
0

Use the while Statement when you have to check a condition repeatedly and only when the condition is satisfied execute the loop

while(condition) //eg. a>5
{
Body of Loop
}
  • If you see the flow of control here you can see that the condition is checked before the execution of the loop, if the condition is not met the loop will not execute at all

In the Do-While statement the program will execute the body of the loop once and then it will check if the statement is true or not

do
    {
Body of Loop
}

while(condition); //eg. a>5
  • If you notice the flow of control here you will see that the body is executed once, then the condition is checked. If the condition is False the Program will break out of the loop, if True it will continue executing till the condition is not satisfied
  • It is to be noted that while and do-while give the same output only the flow of control is different
0

/* while loop

5 bucks

1 chocolate = 1 bucks

while my money is greater than 1 bucks 
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1
end

come to home and cant go to while shop because my money = 0 bucks */

#include<stdio.h>
int main(){
  int money = 5;

  while( money >= 1){   
    printf("inside the shopk and selecting chocolate\n");
    printf("after selecting chocolate paying 1 bucks\n");
    money = money - 1 ;  
    printf("my remaining moeny = %d\n", money);
    printf("\n\n");
  }

  printf("dont have money cant go inside the shop, money = %d",  money);

  return 0;
} 

infinite money

while( codition ){ // condition will always true ....infinite loop
  statement(s)
}

please visit this video for better understanding https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s

0

It is very simple to distinguish between the two. Let's take While loop first.

The syntax of while loop is as follows:

// expression value is available, and its value "matter".
// if true, while block will never be executed.
while(expression) {
    // When inside while block, statements are executed, and
    // expression is again evaluated to check the condition. 
    // If the condition is true, the while block is again iterated
    // else it exists the while block.
}

Now, let's take the do-while loop. The syntax of do-while is different:

// expression value is available but "doesn't matter" before this loop, & the 
// control starts executing the while block.
do {
   // statements are executed, and the
   // statements is evaluated and to check the condition. If true 
   // the while block is iterated, else it exits. 
} while(expression);

A sample program is given below to make this concept clear:

public class WhileAndDoWhile {

  public static void main(String args[]) {
    int i = 10;
    System.out.println("While");
    while (i >= 1) {
        System.out.println(i);
        i--;
    }
    // Here i is already 0, not >= 1.
    System.out.println("do-while");
    do {
        System.out.println(i);
        i--;
    } while (i >= 1);
  }
}

Compile and run this program, and the difference becomes apparent.

Balepur
  • 138
  • 1
  • 7