user1095058
user1095058

Reputation: 75

In a nested for loop, how can we return to the first loop from second loop?

I have 2 loops like the code below:

for(NSString *link in pageLinks){

    for(NSString *pattern in disallowedPattern){

        if (range.location != NSNotFound )
           // if condition is yes go back to the first loop.
    }

}

I want the program to return to the first loop if the condition is yes. I used continue, but it just returns to the second loop. What is the solution to this?

Upvotes: 1

Views: 3586

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753615

A break; in the inner loop resumes the outer loop immediately after the inner loop.

for (NSString *link in pageLinks)
{
    for (NSString *pattern in disallowedPattern)
    {
        if (range.location != NSNotFound) 
            break;
    }
    ...execution continues here after break is executed...
}

There's a question lurking in the comment:

That is exactly the other problem that I've got; [I want to skip the] 'something' after the second for loop as well; is there any solution to this again?

I hope I've interpreted it correctly. There are two possibilities, at least. Which you choose depends in part on your attitude to goto statements.

Either (with goto)

    for (NSString *link in pageLinks)
    {
        for (NSString *pattern in disallowedPattern)
        {
            if (range.location != NSNotFound) 
                goto end_of_outer_loop;
        }
        ...other code to be executed if the loop terminates...
end_of_outer_loop: ;    // Null statement after the colon
    }

Or (without goto)

    for (NSString *link in pageLinks)
    {
        bool found = false;
        for (NSString *pattern in disallowedPattern)
        {
            if (range.location != NSNotFound)
            {
                found = true; 
                break;
            }
        }
        if (!found)
        {
            ...other code to be executed if the loop terminates...
        }
    }

Both work; both are reasonably clear. It is mostly a matter of taste which you choose.

Upvotes: 2

asaelr
asaelr

Reputation: 5456

You should use break. The continue keyword just restart the current loop. (In for loops, continue will do the increment before restarting.)

Upvotes: 3

JustSid
JustSid

Reputation: 25318

break is what you want. It will terminate the current loop and, in your case, get back to the first one.

Upvotes: 7

Related Questions