How can I exit a for loop without the use of break?

Hi, I've written code to swap integers in multiple arrays and I was wondering is it possible to exit this for loop without the use of break and keeping the logic consistent?

Thanks ahead of time for the help.

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
26
27
28
29
30
31
32
void swap(int** arrays, int arraycount) 
{
	for (int first = 1; first < arrays[0][0] + 1; ++first)
	{
		int swapped = 0;
		if (arrays[0][first] % 2 == 0)
		{
			cout << arrays[0][first] << " is odd " << endl;
			for (int i = 1; i < arraycount; ++i)
			{
				for (int j = 1; j < arrays[i][0] + 1; ++j)
				{
					if (arrays[i][j] % 2 != 0)
					{
						int temp = arrays[i][j];
						cout << "Array #" << 1 << " value " 
							<< arrays[0][first] << " swapped with "
							<< "Array #" << i << " value " << temp;
						
						arrays[i][j] = arrays[0][first];
						arrays[0][first] = temp;
						swapped = 1;
						break;
					}
				}
				if (swapped) {
					break;
				}
			}
		}
	}
}
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/175137/
Don't duplicate posts please. To answer your question, not that I know of...
Your options are continue, return, and goto.

A break is a thinly-disguised goto. As long as you don't do something weird (that is, use it like a break), a goto would be fine here.

Hope this helps.
Your options are continue, return, and goto.

Or you could use sentinel flags as part of your loop conditions, setting their values appropriately within the body of the loop to control whether or not the loop continues.

1
2
3
4
5
6
7
8
9
10
// A loop that only loops 10 times, even though it looks like it will loop 1000 times
bool keep_looping = true;
for (int i = 0; i < 1000 && keep_looping; ++i)
{
    std::cout << "I have looped " << i << " times " << std::endl; 
    if (i > 9)
    {
         keep_looping = false;
    }
}
Last edited on
Or perhaps modify the condition in the for loops
1
2
3
    for (int i = 1; (i < arraycount) && !swapped; ++i)
    {
        for (int j = 1; (j < arrays[i][0] + 1) && !swapped; ++j)
Last edited on
Topic archived. No new replies allowed.