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
Related
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.
Is there is any difference to put most probable condition in if, else-if or else condition
Ex :
int[] a = {2,4,6,9,10,0,30,0,31,66}
int firstCase = 0, secondCase = 0, thirdCase = 0;
for( int i=0;i<10;i++ ){
int m = a[i] % 5;
if(m < 3) {
firstCase++;
} else if(m == 3) {
secondCase++;
} else {
thirdCase++;
}
}
What is the difference of the execution time with input
int[] a = {3,6,8,7,0,0,0,0,0,0}
Is there is any different to put most possible true condition in if, else-if or else condition
Actually, the answer with Java is that "it depends".
You see, when you run Java code, the JVM starts out by using the using the interpreter while gathering statistics. One of the statistics that may be recorded is which of the paths in a branch instruction is most often taken. These statistics could then used by the JIT compiler to influence code reordering, where this does not alter the compiled code's semantics.
So if you were to execute your code, with two different datasets (i.e. "mostly zero" and "mostly non-zero"), it is possible that the JIT compiler would compile the code differently.
Whether it can actually make this optimization depends on whether it can figure out that the reordering is valid. For example, can it deduce that the conditions being tested are mutually exclusive?
So how does this affect the complexity? Well ... lets do the sums for your simplified example, assuming that the JIT compiler doesn't do anything "smart". And assume that we are not just dealing with arrays of length 10 (which renders the discussion of complexity moot).
Consider this:
For each zero, the loop does one test and one increment - say 2 operations.
For each non-zero element, the loop does two tests and one increment - say 3 operations.
So that is roughly 2*N operations for N elements when all zero versus 3*N operations ehen all non-zero. But both are O(N) ... so the Big O complexity is not affected.
(OK I left some stuff out ... but you get the picture. One of the cases is going to be faster, but the complexity is not affected.)
There's a bit more to this than you're being told.
'if' versus 'else': If a condition and its converse are not equally likely, you should handle the more likely condition in the 'else' block, not the 'if' block. The 'if' block requires a conditional jump which isn't taken and a final branch around the 'else' block; the 'else' block requires a condition branch which is taken and no final branch at all.
'if' versus 'else if' versus 'else': Obviously you should handle the most common case in the 'if' block, to avoid the second test. The same considerations as at (1) determine that the more common case as between the final 'else if' and the final 'else' should be handled in the final 'else' block.
Having said all that, unless the tests are non-trivial, or the contents of all these blocks are utterly trivial, it it is rather unlikely that any of it will make a discernible difference.
There is no difference if you only have an if-else, since the condition will always be evaluated and it does not matter whether it is almost always true or false. However, if you have an if in the else part (the else if), it is much better to put the most possible true condition in the first if. Therefore, most of the time you won't need to evaluate the condition inside the else, increasing performance.
If most conditions are true in if then the execution time will be less .Because in the first if condition only it satisfied.
If most conditions are true in if-else then the execution time will be less then last and more than first scenarios .
If most conditions are true in else then the execution time will be more.Because it checkes first 2 conditions.
Sure it is.
if ... else if ... checks are going in order in which they were coded. So, if you will place most possible condition in the end of this conditions checking queue - such code will work slightly slower.
But it all depenends how these conditions are built (how complex they are).
Most Possible condition should go to the if and then if else and so on.
It's good to write the most common condition in the very first level so that if that condition is true or false will be treated first in less time.
If you put the most frequent condition in middle (else..if) or in last (else), then it will take time to reach to that condition statement because it needs to check every condition statement.
The following is part of the code for my college assignment.
else if (!codeList.contains(userCode)) {
i--; // i is the counter for the for-loop
}
else if (userQuantity[i]==0) {
i--;
}
The first part makes sure that if the user enters the wrong code, the counter i does not increment 1, or rather, it subtracts 1 from the recently incremented counter. This part works fine.
The second part however is what I seem to be having problems with. userQuantity[] is an int array and it has to be an array. This does not seem to do anything to the code. Even if 0 is entered for the quantity, it still incrememnts the counter which is not desireable.
I should explain, to avoid confusion, that this is an infinite for-loop (with a break statement). The reason I am doing a for-loop is because I am required to. Is it because of my for-loop that the condition isn't working or am I doing something completely wrong with it?
This is for my college assignment so I would appreciate answers with explanation and not just quick-fixes. If you need me to explain, let me know please.
Although it's not strictly illegal in Java, it's not a good idea to change the value of the for loop control variable from within the loop. (Such modification is illegal in some other languages.)
By changing the loop iteration variable within the loop, you're messing with the implicit assumptions offered by your use of a for loop. For example, if a reader sees:
for (int i = 0; i < 10; i++) {
// ...
}
the reader will rightfully assume that the loop is intended to execute exactly 10 times (or, no more than 10 if there is a break in there). However, if you go changing the value of i within the loop, this assumption is no longer valid.
If you must change the value of the counter, I would suggest writing this as a while loop instead:
int i = 0;
while (i < 10) {
// ...
i++;
}
along with a comment that explains why you are changing i within the loop and what it means to do so.
This is very bad practice. Change the for loop to a while loop and only increment if
codeList.contains(userCode)==true or userQuantity[i]!=0.
I should explain, to avoid confusion, that this is an infinite for-loop (with a break statement). The reason I am doing a for-loop is because I am required to. Is it because of my for-loop that the condition isn't working or am I doing something completely wrong with it?
I have a feeling that you are misunderstanding the requirements (e.g. you are not required to use a for loop), or that there is a mistake in your thinking; i.e. there is a simpler solution that doesn't involve the counter going backwards.
(It is surprising that a programming exercise would require you to write code that most experienced Java programmers would agree is bad code. The simple explanation is that it is not.)
Either way:
Changing the loop variable in a for loop is bad practice, for the reasons described by Greg.
The idea of an "infinite for loop" is really strange. The following is legal Java ...
for (int i = 0; true; i++) {
...
}
but the idiomatic way to write it is:
int i = 0;
while (true) {
...
i++; // ... at the appropriate point / points
}
... which in most cases means that you don't need to make the variable go backwards at all.
I am looking at somebody else's code and I found this piece of code:
for (;;) {
I'm not a Java expert; what is this line of code doing?
At first, I thought it would be creating an infinite loop, but in the very SAME class this programmer uses
while(true)
Which (correct me if I'm wrong) IS an infinite loop. Are these two identical? Why would somebody change their method to repeat the same process?
Any insight would help,
Thanks!
Remember the three clauses of the for() are [1] initialization [2] termination and [3] increment. Since the termination clause is empty the loop never terminates. This is directly taken from C syntax.
Those two lines would have the same effect. I can't think of a good reason to use the first one unless you like to confuse people. I guess it's less characters.
they are entirely the same the only real difference would be either preference (the for construct can be typed marginally faster)
or the for indicates that is is some iteration that is broken out of by a break or return and a while loop indicates a repeating section of the same thing until a meaningful result appears
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.