breaking out of a loop

Hello, I am wondering if there is a way to do this: I have 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
25
#include <iostream>
using namespace std;

int main()
{
	int arr[10], stopper, j=0, hold;

	cout << "Please enter 10 numbers\n";

	for(int i = 0; i<10; i++)
		cin >> arr[i];

	for(int i = 1; i<10; i++)
	{
		while(arr[j] > arr[i])
		{
                    if(i<0)
                        break;
 
                }
			
	}
system("pause");
return 0;
}


Now here is my problem, when I do the break in the if inside the while it will break all loops even the for loop outside and I only want it to break up to the while loop and stay in the for loop. Is this possible? I am doing an insertion sort example with this program.
How do you know that the program is jumping out of both loops? Based on your code, it should only break if i is less than zero.
Your for loop, however, initializes i to one, and increments it, so i will never be zero, so that if statement should always fail.
If you're unsure, but the break inside brackets {}.

Put some code in your loop to see where it is breaking out so you can see what is going on. You can put in a a simple cout statement so that some output will be generated during the loops iteration.

It doesn't really matter what the output is, just as long as you can tell which iteration each statement is for.

1
2
3
4
5
6
7
8
9
10
for (int i = 1; i < 10; i++)
{
    int loopIterationNumber(1);
        while (arr[j] > arr[i])
        {
                if (i<0)
                        break;
        }
    cout << "Loop number " << loopIterationNumber << endl;
}


I didn't copy all of your code, but that's one way you can track a loop.

You won't know if your program is breaking out of all of the loops unless you can have the program output something.

A break statement will only break out of the innermost loop. Multiple break statements would be necessary to break out of all the loops.
have a boolean rather than a break

1
2
3
4
5
6
7
8
9
10
11
12
bool bLoopDone(false)
while(<someCondition> || bLoopDone)
{

....

    if(i<0)
    {
        dLoopDone = true;
     }

}


something like that.
Topic archived. No new replies allowed.