12,454,164 members (59,326 online)
Rate this:
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....
here is my code...in 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 29-Sep-12 7:22am
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?

Rate this:

## Solution 1

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

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

Top Experts
Last 24hrsThis month
 Maciej Los 235 OriginalGriff 210 Member 12658776 90 Bernhard Hiller 80 Dave Kreskowiak 75
 OriginalGriff 6,373 ppolymorphe 3,878 Karthik Bangalore 3,635 Maciej Los 3,480 Richard Deeming 2,835