While browsing questions and answers in this forum i found a piece of code were names were given to loops in order to use them for break. Like
nameofloop:
for(){
for(){
if(){ break nameofloop;}
}
}
Im new to programming and i havent seen that before. My question is what other uses of naming loops are there?
This is not a labeled loop, is just a label that you place anywhere and then you can "break" or "continue" to depending on your conditions. You can also use in a nested if-else with for loopings in order to break several loops decorated with if-else, so you can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.
Its use is discouraged as resembles a goto and causes spaghetti-code.
Personally I used only once, time ago, in order to break a for loop inside other two for loops with if-else and continue in the outer loop, as break inside a loop breaks this loop, but you continue in the outer loop, not the most-outer that was my case.
You can also say:
continue nameofloop;
...to jump to start of the named loop. I don't think there are any other use cases for labels in Java.
It's known as a labelled break which is a form of branching statement. You can see all the examples in the Official Documention.
Officially, I believe this is called a "labeled break". It's useful for breaking out of nested loops, such as:
found:
for (int i = 0; i < 100; i++)
for (int j = 0; j < 100; i++)
if ( /* Some condition is met */)
break found;
I don't think it's useful for anything else.
I think it's the only case it's used. And it's not something which is commonly used, because it's usually more readable to change the value of a flag to end a loop prematurely.
Create an array (int) of size 10.
Let the user assign the values - (use for-loop).
Find the total and average of the values stored in the array - (use for- loop).
Related
Whilst browsing the Apache ActiveMQ source code, i came across a funny looking for loop..
for (;beforeEndIndex < size;) {
synchronizations.get(beforeEndIndex++).beforeEnd();
}
Whats the benifit of this over using a standard while loop?
E.G.
while(beforeEndIndex < size){
beforeEndIndex++;
}
Both do exactly the same thing.
The major difference between a for loop and a while loop is that the for loop limits the scope of the iteration counter to within the for block where as a while loop requires you to declare the iteration counter at least one block higher. In this case, as the for loop declares no iteration counter variable, there is no difference.
Can I use break on a nested for-loop to get back to outer while-loop and use continue from inside the for-loop to force the while-loop to keep going? I can not get the for-loop conditions into my while-loop conditions so the while-loop might stop if I cannot continue on a specifically meet situation.
while(...some conditions...){
...print stuff
for(...some instances are arrays, condition loop array...){
if(...index meets conditions...){
...print once, some arrays might meet condition on multiple index
break; //to prevent multiple printings
}
continue; //i don't want to force another while iteration if(false)
//or is this continue for(loop) anyway?
}
continue; //is this not essentially a while(true) loop with no return?
}
The reason I can not get the for-loop conditions into the while conditions is because there are more if conditions between the two loops like if(array == null) and if-condition x == true getArray() needs to be called if array is not passed in. Most of the time condition y and z print from while-loop but sometimes condition x is met so I need the for-loop. It's after the printing of the for-loop if(index true)) I need the while-loop to go again that I'm stuck with? Sometime this might happen from while-loop conditions anyway but I can see that it wont always, further more if for-loop if(index false)) is meet I don't want to force the while loop as this could get costly in run time processing and could possibly result in an endless loop.
PS I am a junior programer, I'm not even sure it this is possible?
or makes sense, sorry if its a stupid question
you can name your loops like this:
namedLoop: for(...) {
// access your namedloop
break namedLoop;
}
You can break with label.
Here is a complete example showing it:
https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/BreakWithLabelDemo.java
Basically the code is similar to this:
:myLabel
for (...) {
for(...) {
...
break myLabel; // Exit from both for loops
}
}
continue and break apply to the immediate current scope, so if you're inside the for, it will apply to the for.
You can store the comparison result on a boolean variable to check if you want to continue.
I'm not a big fan of break and continue, it hinders readability in my opinion. You can acheive the same behavior using a different code structuring.
This question already has answers here:
for loop VS while loop in programming languages, c++/java?
(9 answers)
Closed 9 years ago.
Some iteration code is written like this
while(true) for(int i = 0 ; i<=4;++i)
{
{
System.out.println(i); System.out.println(i);
if(i==4)
break;
}
}
both have the same logic inside it take it as assumption. So which one will be faster, better to use in code and what are the implication of using any one of it??
The first one is an endless loop :) (depending on the i before the loop) The second one does (almost) what you expect. Go grab a good manual about your programming language, it will explain the difference.
On another level: Loop optimizations are much better suited to for loops (AFAIK) so a "clever" compiler might generate better code for the "for" loop. http://en.wikipedia.org/wiki/Loop_optimization
They are totally different, but if their behavior was the same, never use break; in such situations.
The second bucle is more clear, when you have to take into consideration performance, you don't have to do it in retreat of clean code.
The second bucle is self-documented while the first you need to add a reason to add the break in order to be understandable.
to end the while loop on the left you have to incriment i
EDIT : Assuming i is less that 4 when the loop starts
For that purpose, use a for one, since you need the value of i. It is more understanding for maintenance. Anyway, the compiler will optimize both codes and runtime may be the same.
Considering your while is not an infinite loop there is no difference as far as performance is concerned. However, I personally prefer for loop as it is cleaner. Consider this:
int i = 0;
while (true) {
doSomething(i++);
if (i == 4)
break;
}
which looks cleaner with
for (int i = 0; i <= 4; i++)
doSomething(i);
Im using for whenever I know the number of itterations in advance.
If you know how many time you want to do some operation you have to use for loop otherwise use while loop.
For example:
If you have some array or arraylist then suppose you want to add all
elemnts of it then you should use for loop because you know size of
arraylist by size() function and know the size of array by length
attribute.
If you have resultset and you want to retrieve all rows from it then
you should use while loop because you don't know how many element in
resultset object.
Neglecting the typo of your question,Assuming that you want to know which one i choose when Both loops are essentially doing the same thing.
The answer is you can go for any one.
But it's better to use for loop if you know how many times you want to run a loop as you can set the condition during initialization. And in future also it will be easy to change it if you want to extend the iteration.
You can prefer while if you are not sure for how much iteration you want. In your case i will go with for loop
Note: the answer is opinion based.
in Java, when using a for loop, you need to write a termination condition of course. This is my for loop:
for(int i=1; i<=infix.length()-2; i++){
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
(infix is a string i got as a parameter). As you can see, I'm using substring inside the loop, which shortens the length of infix, which means that the termination condition of the loop is changed after every single iteration.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i? When will the for stop? Is there a chance for an index out of bounds or something like that?
Thank you very much in advance! :D
The string length gets calculated every loop, and your for could throw an IndexOutOfBoundsException if your string becomes too short.
IMHO yours is a very bad practice, for loops are intended to make a determined number of loops and should never be stopped, also their stop condition should never be changed inside the loop, you should use a while if you don't know how many iterations you want to do. But this is my personal opinion :)
Yes, you can change the upper limit. No, it's not cached at the beginning of the loop. Yes, anything you do wrong might cause errors -- but this is neither especially dangerous or uncommon. On the contrary, it's quite common.
you can put multiple end criteria in a for loop, just for a sample syntax
for(int i = 0; i < 2 || i< 5; i++)
System.out.println(i);
As a short hint: Your for-loop is equivalent to the following while-loop
{
int i=1;
while(i<=infix.length()-2) {
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
i++
}
}
That means the condition of a the for-loop is evaluated in the same way as the condition of a while-loop. There is nothing special about it.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i?
It changes with every iteration of the for loop. i gets incremented, with each iteration.
When will the for stop? Is there a chance for an index out of bounds or something like that?
The for loop will stop when the termination condition is true.
i<=infix.length()-2.
i initialized to 1 will result in a loop that terminates if the length
If you modify the termination condition variables with incorrect logic, then you have a chance of running into an infinite loop.
I am learning java as well android. Almost everything that we can perform by while loop those things we can do in for loop.
I found a simple condition where using while loop is better than for loop
if i have to use the value of counter in my program then i think while loop is better than for loop
Using while loop
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter); // method which use that value of counter do some other task
In this case I found while loop is better than for loop because if i want to achieve the same in for loop i have to assign the value of counter to another variable.
But is there any specific situation when while loop is better than for loop
One main difference is while loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can use for loop.
A for loop is just a special kind of while loop, which happens to deal with incrementing a variable. You can emulate a for loop with a while loop in any language. It's just syntactic sugar (except python where for is actually foreach). So no, there is no specific situation where one is better than the other (although for readability reasons you should prefer a for loop when you're doing simple incremental loops since most people can easily tell what's going on).
For can behave like while:
while(true)
{
}
for(;;)
{
}
And while can behave like for:
int x = 0;
while(x < 10)
{
x++;
}
for(x = 0; x < 10; x++)
{
}
In your case, yes you could re-write it as a for loop like this:
int counter; // need to declare it here so useTheCounter can see it
for(counter = 0; counter < 10 && !some_condition; )
{
//do some task
}
useTheCounter(counter);
for and while are equivalent, just a different syntax for the same thing.
You can transform this
while( condition ) {
statement;
}
to this:
for( ; condition ; ) {
statement;
}
The other way:
for( init; condition; update) {
statement;
}
is equivalent to this:
init;
while(condition) {
statement;
update;
}
So, just use which looks better, or is easier to speak.
Remember,
Everything done with a for loop can be done with a while loop, BUT not
all while loops can be implemented with a for loop.
WHILE :
While-loops are used when the exiting condition has nothing to do with the number of loops or a control variable
FOR :
for-loops are just a short-cut way for writing a while loop, while an initialization statement, control statement (when to stop), and a iteration statement (what to do with the controlling factor after each iteration).
For e.g,
Basically for loops are just short hand for while loops, any for loop can be converted from:
for([initialize]; [control statement]; [iteration]) {
// ...
}
and
[initialize];
while([control statement]) {
//Do something [iteration];
}
are same.
Use a FOR loop when you know the number of times you want to loop. The technical term for that is the number of iterations. How do you know the number of iterations? You know the start, stop and step. If you know those three pieces of information, you should use a FOR loop because it's the right tool for the job.
Use a DO loop when you don't know the number of iterations. If you don't know the start, stop, step or some combination of those then you need to use a DO loop. The expression will be evaluated at the top of the loop.
Use a DO WHILE loop if you want to loop at least once. Use just a WHILE loop if you don't want to loop at least once. The expression will be evaluated at the bottom of the loop.
for is finite, in the sense that it will finish looping when it runs out of elements to loop through....
while can be infinite if a condition isn't met or the loop broken
Edit
My mistake ... for can be infinite ..
The while loop is generally better when you don't have an iterator (counter usually).
One thing I feel I should point out is that when you use a for loop, you do not need to assign counter to another variable. For example for(counter=0; counter<10; counter++) is valid Java code.
As for your question, a for loop is usually better when you want a piece of code to run a certain number of times, and a while loop is better when the condition for the code to keep running is more general, such as having a boolean flag that is only set to true when a certain condition is met in the code block.
You can do something like:
int counter;
for (counter = 0; counter < 10; ) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter);
Anything that a while-loop can do, can also be done in a for-loop, and anything a for-loop can do, can also be done in a while-loop.
No. There's not a specific situation where for is better than while.
They do the same thing.
It's up to you choose when apply one of those.
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
}
useTheCounter(counter); // method which use that value of counter do some other task
Hi I repeat your code because it is incorrect. You forget to increase your counter so it will remains on 0
int counter = 0;
while (counter < 10) {
//do some task
if(some condition){
break;
}
counter++;
}
useTheCounter(counter); // method which use that value of counter do some other task
while loops are much more flexible, while for loops are much more readable, if that's what you're asking. If you are wondering which one is faster, then look at this experiment I conducted concerning the speed of for and while loops.
https://sites.google.com/a/googlesciencefair.com/science-fair-2012-project-96b21c243a17ca64bdad77508f297eca9531a766-1333147438-57/home
while loops are faster.
What ever you can write in for loop can be converted to while loop. Benefits of using for loop are
The syntax allows you to start a counter, set the condition to exit loop, then auto increment.
You can get the same done in while loop also. But all which you can do in while loop is not possible to do in for loop. For example if you have more than one counter and you want any of them to increment based on a condition then while only can use. In for loop at the end of loop the counter increment happens automatically.
Best use
For matrix or single array single directional traversal, for loop is good
In case of multiple conditions and multiple counters then while loop is good. if yuo want to traverse an array from both sides based on different conditions then while loop is good.
While loop, there is lot more chance to forget increment counter and ends up into infinite loop, while in for loop syntax will help you to easily set the counter.
For loops include the notion of counting, which is great. Yet, when you don’t know how many times the code should run, while loops make sense.