Continue statement in nested loop

Hello,
I was wondering how I could use a continue statement that continues in a nested loop.
For example if I have
1
2
3
4
5
6
7
8
9
for (int i=0;i<amount;i++) {
	for (int j=0;j<I[i];j++) {
		for (int k=j+1;k<I[i];k++) {
			if (P[i][j]+P[i][k]==C[i]) {
				//What should be here?
			}
		}
	}
}


If the condition is met then the most outer loop (in i) should continue to the next iteration.
If i simply fill in continue; in before the comment then it only continues the loop in k so that is not what I want.

Can anyone help me out please?
Thanks in advance,
Jannes
You have a number of nested iterations. Which one to you want to go back to?
"then the most outer loop (in i) should continue to the next iteration."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (int i = 0; i < amount; i++)
{
	for (int j = 0; j < I[i]; j++)
	{
		for (int k = j + 1; k < I[i]; k++) 
		{
			if (P[i][j]+P[i][k]==C[i]) 
			{
				j = I[i];
				break;
			}
                }
	}
}
Last edited on
@Smac89 I believe that will break to the middle j loop not the outer i loop.

I think goto is appropriate here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (int i = 0; i < amount; i++)
{
	for (int j = 0; j < I[i]; j++)
	{
		for (int k = j + 1; k < I[i]; k++) 
		{
			if (P[i][j]+P[i][k]==C[i]) 
			{
				j = I[i];
				goto outer;
			}
	}
outer:
}
Don't use goto, just to exist from a loop. Some say never use goto at all, I don't necessarily agree, but this is a supporting case.

For example, if you use a goto, you can't break those loops into different functions. It's all bad.

Use a flag to get back:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for (int i = 0; i < amount; i++)
{
	bool check_next = false;

	for (int j = 0; !check_next && j < I[i]; j++)
	{
		for (int k = j + 1; !check_next && k < I[i]; k++) 
		{
			if (P[i][j]+P[i][k]==C[i]) 
			{
				j = I[i];
				check_next = true;
			}
                }
	}
}
Last edited on
Topic archived. No new replies allowed.