Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
i make a program for 3n+1 problem..
this program give right output
but the problem is that there is while loop which never terminate.
i want terminte the while loop on certain condition..
suppose if i enter 0 while loop termintate....plz modify this code....
thanks in advnce...
here is my code...in c++

C#
#include <iostream.h>

#include<conio.h>

int cycle( long int n)
{
      long int i = 1;

    while(n != 1) {
        if(n % 2 == 0)  {
            n=n/2;
        } else {
            n= (3*n)+1;

        }
        i++;
    }
    return i;
}

int main()
{
    int a, b, low, high,ch;
     cout<<"enter the series of numbers";

    while(cin>>a>>b) {

        if(a < b) {
            low = a;
            high = b;
        } else {
            low = b;
            high = a;
        }

        int max = cycle(low);

        for(int i = low + 1; i <= high; i++) {
            int l = cycle(i);
            if(l > max) {
                max = l;
            }
        }

        cout<<a<<" "<<b<<" "<<max<<"\n";
               }
     getch();
    return 0;

}
Posted
Comments
Sandeep Mewara 29-Sep-12 14:18pm    
i want terminte the while loop on certain condition..suppose if i enter 0 while loop termintate....plz modify this code....
Did you try? What happened when you did?

1 solution

Please use extra if condition and check the mod value with zero equating status.

C#
while(n != 1)
    {
        if(n % 2 == 0  && n != 0 )
        {
            n=n/2;
        }
        else if( n == 0 )
        {
            return 0;
        }
        else
        {
            n= (3*n)+1;
        }
        i++;
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900