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
0 OriginalGriff 527
1 CPallini 510
2 Sergey Alexandrovich Kryukov 438
3 George Jonsson 271
4 Afzaal Ahmad Zeeshan 184
0 OriginalGriff 5,370
1 CPallini 4,360
2 Sergey Alexandrovich Kryukov 3,822
3 George Jonsson 3,037
4 Gihan Liyanage 2,435


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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100