This question already has answers here:
Why use a "do while" loop? [closed]
(9 answers)
Closed 1 year ago.
I know what do does, and how it cooperates with the while loop, but won't a while loop code be the same, whether or not the do is there?
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();
}
The biggest difference between while and do-while statement is, whether it is executed at least one time or not.
while(false)
printf("print!");
with this statement, the program will never print the string. However,
do{
printf("print!");
}while(false);
with this statement, the program will print the string once.
But many people don't recommend to use do-while statement--because it can be substituted with while statement. It doesn't mean that do-while statement is critically harmful, but it is rarely used.
In fact, for loop is the most safe and recommended way because the programmer can handle the iteration number, loop conditions, and increasing variables easily. So if you don't have any specific reason that you have to use while loop, just use for loop.
Use do-while() construct when you have to get your task executed at least once even if condition fails.
Use while() when you your task to be executed only on certain condition success.
The difference is with "do-while" loop will be executed at least one time. With "while" loop with false condition the loop body will not be executed.
if you write the "loop" like so (without the do as in your question):
int i=0;
{
System.out.println(i++);
}while(i<10);
it will just print out 0 (nothing more), and not loop 10 times.. so no, the loop won't be the same if the do isnt there.
Related
I will show you my submitted assignment's answer to give the idea of it
void chkbnch()
{
System.out.println("\n The students under notice period are =>\n\n");
for(int i=0;i<25;i++)
**ol:{**
int cnm=0;
int cnm2=0;
for(int j=0;j<7;j++)
{
if(mrks[i][j]>=50)
{
cnm++;
}
if(cnm==3)
{
//i++;
**break ol;**
}
if(mrks[i][j]<50)
{
cnm2++;
}
}
if(cnm2>=3||cnm<3)
{
System.out.println("\n Student id =>"+(i+1));
}
}
}
Here I am using break when I don't want the loop to increment and just repeat the loop statement. I know this can be done by also decrementing the loop control but that's not what my question is.
All I want to ask that is this behaviour defined in java or is it just a chance that this is its outcome.
This use of the break statement is perfectly legal, although it is unusual, and it doesn't do what you say you want.
JLS §14.15 says:
A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a switch, while, do, or for statement.
The "labeled statement" in your example is the {..} block statement, which is the statement executed by the for loop. When you execute the break, that block statement completes, which returns control to the for loop, which continues by executing the increment i++, testing the condition i<25 and then getting on with the loop.
It has the same behavior as labeling the outer loop directly, and then using continue ol;.
The loop counter will still be incremented. If you want to prevent that, either counteract it with a manual i--; or move i++; out of the for loop header and to the end of the loop body.
Seems like you want the continue keyword instead of break. continue breaks the current iteration of the loop and execution jumps back to the evaluation stage where the looping continues if the evaluation passes. break breaks the current iteration of the loop and execution jumps to the first line after the end-of-loop closing brace.
EDIT: If you need the loop increment control to "not increment" when you continue looping, so that, for example, the same object is pulled from the list being looped over after continuing, then you need to roll your own solution.
What does this condition mean in Java?
while(n>0)
I'm a newbie at Java and I've never seen this kind of code in conditions.
just do a search on while loop.
here is a link to wiki
while(n>10)
{
// do stuff..
}
.. simply means execute that block of code as long as n > 10.. normally you would have something inside that code block to make n greater than 10 at some point.. otherwise you would have an infinite loop.. which is bad..
It means that as long as the variable named "n" evaluates to a value greater than 0, what ever logic is inside the while loop code block will continue to execute. FYI - a quick Google search will reveal thorough information and examples on while loops.
the expression inside of a while loop is always a boolean expression;
here you are expressing that a variable, n, is greater than 0.
if true, you enter the loop,
else, you do not.
For a situation like this, it is likely that n is an integer
https://www.tutorialspoint.com/java/java_while_loop.htm
Is it ok to do this to simplify a do-while loop? or should for only be used for incrementing/decrementing?
String res;
for(res=null;res==null;res=op.getOrderID());
instead of:
String res = null;
do {
res = op.getRetOrderID()
} while (res == null);
I think it's better to stick with the do-while loop. This is the standard idiom for the situation when you want the body of the loop to be executed at least once.
One good reason for sometimes using a for loop in preference to a while or do-while loop is that you can make the variable checked in the termination condition local to the loop. You definitely don't want that here as you need it afterwards.
Simple Advice :
use for loop when you know the number of repetitions .
use while loop when you do not know the number of repetitions .
use do-while loop when you want to run your code one time at least and do not know the number of repetitions .
Good Luck .
This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 9 years ago.
What is the meaning of for (;;)?
I found it in a certain base class and I cannot find explanation for in on the net.
Please also explain when and how to use this expression
It's an infinite loop. It has no initial condition, no increment and no end condition.
It's the same as
while(true) {
//do stuff
}
You can use it when you need something to be repeated continuously, until the application ends. But i would use the while version instead
It is read "for ever". the default for the condition is to evaluate to true.
When should you use it? If you don't want the loop to end (as is common in servers) or when the end condition is naturally known only in the middle of the loop, in which case you can use break:
for (;;) {
String in = get_input();
if (in.equals("end"))
break;
System.out.println("you entered " + in);
}
This is not the best example, though. You can do without the infinite loop here. For example:
for (String in = get_input(); !in.equals("end"); in = get_input()) {
System.out.println("you entered " + in);
}
It means an infinite loop. It is not considered a good practice to use this. Instead try while(true)
In some cases where you want to do a task again and again, sometimes forever. Such cases you use an infinite loop. This can be done in many ways. Notable ones are,
Using while,
while(true)
{
// Task you want to repeat
}
Using for,
for(;;)
{
// Task you want to repeat
}
Note : You might have to be very much careful while implementing infinite loops as there exists a possibility of same problem recurring. It is a good practice to catch the exception and retry for some time and if still problem persist, break from the loop.
I have a code something like this
Enumeration parameterEnum = request.getParameterNames()
while(parameterEnum.hasMoreElements()){}
what is the difference if I change it from a while statement into an if statement?
If you change it to an if it will either execute once or not at all - a while statement will execute indefinitely until ParameterEnum.hasMoreElements() returns false.
If I understand what you are asking, the current code would keep running whatever is in the brackets until there are not elements. This assumes that what is in the brackets takes off elements. As literally shown above, it is an infinite loop and will never end.
If you convert the while to an if, then what is in the brackets will run only once.
If Request.getParameterNames() returns an "empty" whatever-it-is, then neither case will do anything.
The if will be much, much faster!!! its complexity is O(1) and that of while's is O(N)!!!
So, the larger the input is, the better it is to use an if instead of a while ;-)
You might be thinking of a for statement, not an if.
if(ParameterEnum.hasMoreElements()) {}
The if will only run once
while(ParameterEnum.hasMoreElements()) {}
the while will run continuously, unless you increment the enum.
the other option is for:
for(Enumeration paramEnum = Request.getParameterNames();
parameEnum.hasMoreElements();) {}
this is similar to the while, and will run for as long as the hasMoreElements() method returns true, so incrementing the enum with nextElement() is important.