stopping an infinite loop.
 CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: stopping an infinite loop.

1. Member
Join Date
Feb 2013
Posts
36

## stopping an infinite loop.

The code below gives me the maximum odd number and the minimum even number of a list of numbers that the user type. However, for the loop to stop the user needs to type 1000. Is there a better way (without having to have a "stopping" number, just in case I need this number to be somewhere on the list) to get the same results?

Code:
```#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;

int main()
{

int x, maxi, mini;

cout<<"Enter a list of numbers and 1000 as the last number: ";
maxi=0;
mini=1000;

for(;;)
{
cin>>x;
if(x==1000){break;}
if((x > maxi) && (x%2==1)){ maxi=x;}
else if((x<mini)&& (x%2==0)){mini=x;}
}
cout<<"maximum odd number is: "<<maxi<<endl<<endl;
cout<<"minimum even number is: "<<mini<<endl<<endl;

system("pause");
return 0;
}```

2. ## Re: stopping an infinite loop.

You could stop whenever the user enters something that is not a number. E.g.
Code:
```while (cin >> x) {
// ...
}```

3. Elite Member Power Poster
Join Date
Apr 2000
Location
Belgium (Europe)
Posts
4,626

## Re: stopping an infinite loop.

break is the answer for breaking out of a single loop.

if you need to break out of multiple nested loops:
* you will either need a control variable which is checked on each loop condition
* use goto (though many will frown upon this, it is a valid case for this scenario)
* you can use a try/catch construct around the loop and throw an exception to break out of the loop.
This has benefits over the goto approach in that it will destroy locals, where goto doesn't. Some may find an exception with try/catch overly complex for this scenario. But... it has it's advantages in not having a test in the loop condition which could be significant in time critical code.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Click Here to Expand Forum to Full Width