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.
Related
I want my for loop to have the length a changing number. Can i do that?
I havent really tried anything
for (int i=0; i < colsAdd[i] ; i++){
System.out.print(" 0.0");
}
Actually the colsAdd[0] is the only size.
I'm not sure if I understand exactly what you're asking, but it seems like you're wondering what you are allowed to put into the different parts of a for loop, and the order that they run in.
If we change the code you pasted above to match the diagram below, the rules will become apparent.
for (initialization; condition; updateCounter){
codeInsideLoop
}
Any code can go into those portions of a for loop, they can even be left blank! For instance, the following code is equivalent to a while(true) loop.
for (;true;){
System.out.print("This will run forever!");
}
Or this for loop increments inside of the loop.
for (int i=0; i < 10;){
System.out.print("This will print 10 times");
i++;
}
More in line with your question, this code calls a function each iteration to see if it should continue looping. This function could use any logic to return a boolean value. It will execute at the end of every singe loop regardless.
for (int i=0; keepLooping(i); i++){
System.out.print("This will print 10 times");
i++;
}
Now, just because you can do these things does not mean you should! Generally you want to keep the structure of your loops simple so everyone can understand what your goal is.
[edited the post to be more clear]
The code below is supposed to represent a number of trial runs, and within each trial assume a is the number of cases that need to be checked.
while(testCaseAmt > 0) {
for(int i = 0; i < a; i++) {
if(some condition)
//code when i is not the last element
//then I would like to break/return here.
if(i = a - 1)
//code when i is the last element
//then if the above if statement never runs during the a amt of trials
//i will print out something else
}
testCaseAmt--;
}
My question is if there is another way to access specifically the last element within a for loop to give it specific instructions. I want to loop through a set trials and if they meet the first condition, I stop the loop immediately and return. However, if the condition isn't found I still need to print out not found.
Cheers.
To me this seems related to "off-by-one errors" or "fencepost errors", see here.
If the code you're executing when i is not the last element isn't too complex, it could be better to just end the for loop one iteration earlier and write the specific code for the last element outside the for loop.
Adding an if statement inside a for loop where you know it will only be true at the very last iteration could be seen as bad-style.
You can define a boolean conditionMet = false before the for-loop and iterate until i < a-1.
If some condition applies, execute your code, then set conditionMet = true and break out of the for-loop.
After the for-loop, check if !conditionMet and in this case, execute the code for the last element.
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.
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.