Break and continue nested loops problem.

Hi all,

I have some problems with loops

1
2
3
4
5
6
7
8
9
10
11
12
for (a=3; a<=n; ++a)	// first loop
	{	
		for(i=2; i<a; ++i)	// second loop
		{
			if (Condition)
			{
				break;
			}
			else 
				s=a;
		}
	}


What I want is when the "Condition" is true the second loop will stop and a will raise 1 value in the first loop to start the second loop again. And if i reach max value (this case is a-1), s will equal to a (the first loop still raise a by 1 value). But the code the doesn't seem to work that way.
Last edited on
That is because the break; statement exits the innermost block in which it exists...
Sorry, I can't get it. Can you please tell me more ?
Consider this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream.h>
#include<conio.h>

void main()
{
	clrscr();
	int i=0;
	while (1)
	{
		if (i<1)
		{
			cout<<"1 is true!";
			break;
		}

		if (i<1)
		{
			cout<<"2 is true!";
			break;
		}

	}
	getch();
}


This will output only "1 is true!"
Get the idea? In short, the break; statement exits the next } of the ladder in which it is proceeding.


So in your loop, the break statement only exits the second loop, and then increments i, and enters it again.
What you can do is, if the condition is satisfied, give an int value of 1, and then use break. Then, in the second loop, check for the int==1, and if true, use break. Will serve your purpose...
Topic archived. No new replies allowed.