Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restart a for loop to its first iteration?

In Objective-C, is it possible to restart to the first iteration of a for loop? I don't want to do anything with my objects until I find a "good" object, at which point I want to go back and do stuff with every object up to that good object.

So,

bool someflag = false;
for (id object in array)
{
  if(object is good) 
  {
    someflag = true;
    //restart to first object in loop
  }
  if(someflag)
  {
    doStuffWithObject(object);
  }
}

Or is there a different/better way to do what I'm trying to do?

Obviously the easy way would be to just have two separate for loops -- so if I could get a second opinion telling me that's the best way, that's just what I'll shoot for. For some reason I have a feeling there's got to be a better way, though.

like image 528
A O Avatar asked Jul 15 '14 12:07

A O


People also ask

Can you reset a for loop?

You can reset the value of the loop variable to i = 0 to restart the loop as soon as the user types in 'r' . You use the Python built-in input() function to take the user input in each iteration and return it as a string.

Can we restart a for loop in Java?

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.

Can you restart a loop in Python?

You can use the input() function to restart a while loop in Python. And use the if statement to restart loop count.

How do you redo an iteration in Python?

(The "redo" statement is a statement that (just like "break" or "continue") affects looping behaviour - it jumps at the beginning of innermost loop and starts executing it again.)


2 Answers

Not with fast enumeration, no (with the exception of goto), however if you use the indexed-access approach, you could:

NSUInteger count = [array count];
for (NSUInteger i = 0; i < count; i++)
{
    bool someflag = false;
    id object = array[i];
    if (isgood(object)) 
    {
        someflag = true;
        //restart to first object in loop
        i = 0;
    }
    if(someflag)
    {
        doStuffWithObject(object);
    }
}
like image 85
trojanfoe Avatar answered Oct 02 '22 14:10

trojanfoe


If you really want to do this (rather than using a second loop, which is almost certainly more straightforward), you can use good old goto:

bool someflag = false;
restart:
for (id object in array)
{
  if(!someflag && object is good) 
  {
    someflag = true;
    goto restart;
  }
  if(someflag)
  {
    doStuffWithObject(object);
  }
}
like image 23
Ken Thomases Avatar answered Oct 02 '22 16:10

Ken Thomases