Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a loop "start-over"?

Tags:

  • There is continue; to stop the loop and move to the next loop
  • There is break; to stop the loop and move to the end of the loop

Isn't there some kind of start; that stop the loop and move to the beginning of the loop?

I know it is easy to achieve all of these three actions by just modifying the value of i, but I always try to look for already built-it functions.

like image 576
ajax333221 Avatar asked Jan 07 '12 02:01

ajax333221


People also ask

How do you start over a while loop?

You use the continue statement to restart a loop such as the while loop, for loop or for-in loop. If there are nested loops, the continue statement will restart the innermost loop.

How do you use a loop?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

How do you continue a loop?

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.


2 Answers

Resetting the value of your loop variable to the initial value then calling continue is as close as you'll get.

For example:

for(var i=0; i<20; i++) {   if(somecondition) {     i=-1; continue;   } } 
like image 111
Niet the Dark Absol Avatar answered Oct 09 '22 02:10

Niet the Dark Absol


No - there is no keyword or other way to do it automatically.

As you already mentioned you can just modify the loop condition variable(s) within your loop. Easy if it's a simple i counter, but of course you may have more initialisation to do than just a simple counter.

Or you can do something like the following:

restartLoop: while (true) {    for (var i=0, j=100000, x="test"; i < 1000; i++, j--, x+= ".") {       if (/*some condition, want to restart the loop*/)           continue restartLoop;    }    break; } 

The continue restartLoop will jump back out to continue with the next iteration of the while loop, which then immediately starts the for loop from the beginning including all of the initialisation code. If the for exits normally the break statement after it will break out of the containing while loop.

I don't really recommend doing this in a general sense, but if your loop initialisation process was really complicated it could be worth it because then you wouldn't need to repeat it all inside the loop. If you needed to do even more initialisation than fits nicely in the for statement's initialisation expression you can easily put it just before the for loop inside the while and it will all be re-run...

like image 25
nnnnnn Avatar answered Oct 09 '22 01:10

nnnnnn