# [help] 3n+1 problem

Show 80 post(s) from this thread on one page
Page 2 of 2 First 12
• 12-14-2010
anon
The loop should begin like this:

Code:

```    unsigned i, j;     while(cin >> i >> j)     {     int unsigned k,l,max_cycle=0;```
When entering values from the keyboard (rather than redirecting input to a file), you can indicate end of "file" (input) with a special key combination, e.g on Windows Ctrl+Z.
• 12-14-2010
K12
Changed the loop but still got it wrong. Thanks anon.

Regarding the iostream input buffer, I changed the code to include good(). But the code does not compile, can someone please tell me how to properly use this function.

Code:

```#include <iostream> using namespace std; int CycleLength(int x); int main() {     int unsigned i,j;     bool good();     //i,j are user inputs of the two numbers. k,l store initial values of i and j respectively to be printed out later.     while(good())     {     cin>>i>>j;     int unsigned k,l,max_cycle=0;     k=i;     l=j;     if(i==j)         max_cycle=CycleLength(i);     else     if(i>j)         {             for(i;i>j-1;i--)             {                 if (CycleLength(i)>max_cycle)                 max_cycle=CycleLength(i);             }         }     for(i;i<j+1;i++)     {         if (CycleLength(i)>max_cycle)             max_cycle=CycleLength(i);     }     cout<<k<<" "<<l<<" "<<max_cycle<<endl;     } } int CycleLength(int x) {         int count=1;         while(x>1)         {             if (x%2==!0)                     x=3*x+1;             else                     x=x/2;         count++;         }         return count; }```
• 12-14-2010
anon
By good() it was probably meant the member function cin.good().

However, that would be a wrong way to control an input loop. You'll try to process input even if it fails, because you test for good only at the beginning of the next iteration.

The correct way to control input loops is by testing the result of the input statement, as I've shown.
Show 80 post(s) from this thread on one page
Page 2 of 2 First 12