# stopping an infinite loop.

• February 20th, 2013, 08:59 PM
math8
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; }```
• February 21st, 2013, 05:59 AM
D_Drmmr
Re: stopping an infinite loop.
You could stop whenever the user enters something that is not a number. E.g.
Code:

```while (cin >> x) {     // ... }```
• February 21st, 2013, 11:36 AM
OReubens
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.