Is There Ever a Need for a "Do {...} While ( )" Loop

Is there ever a need for a do {...} while ( ) loop?

Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))

#include <stdio.h>

int main() {
char c;

do {
printf("enter a number");
scanf("%c", &c);

} while (c < '0' || c > '9');
}

This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.

Why use a do while loop?

Your example code is wrong:

do{
document.write("ok");
}while(x == "10"){
document.write("ok");
}

This would be the actual form:

do {
document.write("ok");
} while(x == "10");

You are correct that it executes the inner code block before checking the condition, but it doesn't need to duplicate the inner code block the way you have it. The do/while construct is (as you've already stated) a way to make sure that a piece of code is executed 1 or more times instead of 0 or more times (depending on the conditional).

What is the purpose of a do-while loop?

Consider the following:

while(condition){
myFunction();
}

and

do{
myFunction();
}while(condition);

The second form executes myFunction() at least once then checks the condition! To do so with a while loop you've to write:

myFunction();

while(condition){
myFunction();
}

Are while(true) loops so bad?

I wouldn't say it's bad - but equally I would normally at least look for an alternative.

In situations where it's the first thing I write, I almost always at least try to refactor it into something clearer. Sometimes it can't be helped (or the alternative is to have a bool variable which does nothing meaningful except indicate the end of the loop, less clearly than a break statement) but it's worth at least trying.

As an example of where it's clearer to use break than a flag, consider:

while (true)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
break;
}
actOnInput(input);
}

Now let's force it to use a flag:

boolean running = true;
while (running)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
running = false;
}
else
{
actOnInput(input);
}
}

I view the latter as more complicated to read: it's got an extra else block, the actOnInput is more indented, and if you're trying to work out what happens when testCondition returns true, you need to look carefully through the rest of the block to check that there isn't something after the else block which would occur whether running has been set to false or not.

The break statement communicates the intent more clearly, and lets the rest of the block get on with what it needs to do without worrying about earlier conditions.

Note that this is exactly the same sort of argument that people have about multiple return statements in a method. For example, if I can work out the result of a method within the first few lines (e.g. because some input is null, or empty, or zero) I find it clearer to return that answer directly than to have a variable to store the result, then a whole block of other code, and finally a return statement.

In Java, when is a do while loop the only option?

Is there ever a situation where you must use a do while loop?

No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.

Is it an accepted practice?

If you use it appropriately, then yes absolutely.

It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.

That's right. You can read more about do-while in its tutorial.

Why while(true) is an infinite loop?

Given:

while (a)
{
// b
}

If a is true, then block b will execute. This will keep repeating until a is not true.

If a is replaced with the constant value true, then a will never be false so the loop will never quit.

What condition does while(true) test? When is it true and false?

When is while(true) true, and when is it false?

It's always true, it's never false.

Some people use while(true) loops and then use break to exit them when a certain condition is true, but it's generally quite sloppy practice and not recommended. Without the use of break, return, System.exit(), or some other such mechanism, it will keep looping forever.

When would a do-while loop be the better than a while-loop?

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 */ );

How do I add a delay in a JavaScript loop?

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

You may want to use something like this instead:

var i = 1;                  //  set your counter to 1

function myLoop() { // create a loop function

setTimeout(function() { // call a 3s setTimeout when the loop is called

console.log('hello'); // your code here

i++; // increment the counter

if (i < 10) { // if the counter < 10, call the loop function

myLoop(); // .. again which will trigger another

} // .. setTimeout()

}, 3000)

}

myLoop(); // start the loop


Related Topics



Leave a reply



Submit