CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Hybrid View

  1. #1
    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. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: stopping an infinite loop.

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

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    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

Featured