Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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++
 
#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
Comments
Sandeep Mewara at 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

Rate this: bad
good
Please Sign up or sign in to vote.

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++;
    }
  Permalink  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Shai Vashdi 1,858
1 Tadit Dash 330
2 OriginalGriff 278
3 Sergey Alexandrovich Kryukov 275
4 Manas Bhardwaj 249
0 Sergey Alexandrovich Kryukov 9,530
1 OriginalGriff 5,711
2 Peter Leow 4,320
3 Maciej Los 3,540
4 Abhinav S 3,373


Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 13 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid