2
    #include<iostream>
    using namespace std;
    class ulam
    {
        int num;
        double prod;
        int cot;
    public:
        ulam(){cot=0;}
        ulam(int x)
        {
            num=x;
        }

        void process()
        {
          for(int i=0;num==1;i++)
          {
            cout<<num<<endl;
            if((num%2) == 0)
            {
              prod=num/2;
            }
            else
            {
              prod=(3*num)+1;
            }
            num=prod;
            cot++;
          }
        }
        void display()
        {
            cout<<"the number of steps required is: "<<cot;
        }
    };
    int main()
    {
        int n;
        cout<<"enter the number"<<endl;
        cin>>n;
        ulam obj(n);
        obj.process();
        obj.display();
    }

when i write this code the cot value comes as a garbage value i think. i cant figure out where i went wrong. i used class because i feel it is more discriptive . but the main aim behind this program is to find the number of steps it is required for a number to reach one and to print the whole sequence of numbers. for thos who dont know about the collatz conjecture https://en.wikipedia.org/wiki/Collatz_conjecture

2 Answers2

1

Your condition of the for loop inside process function is wrong. it should be num!=1. You need to initialize cot too. You don't need prod actually.

#include<iostream>
using namespace std;
class ulam
{
    int num;
    int cot;
public:
    ulam()
    {
        cot=0;
    }
    ulam(int x)
    {
        cot=0;
        num=x;
    }

    void process()
    {
      for(int i=0;num!=1;i++)
      {
        cout<<num<<endl;
        if((num%2) == 0)
        {
          num=num/2;
        }
        else
        {
          num=(3*num)+1;
        }
        cot++;
      }
    }
    void display()
    {
        cout<<"the number of steps required is: "<<cot;
    }
};
int main()
{
    int n;

    cout<<"enter the number"<<endl;
    cin>>n;
    ulam obj(n);
    obj.process();
    obj.display();

    return 0;
}
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
0

First Problem

In the constructor where you initialize when an integer is passed, you ALSO have to initialize cot like this:

ulam(int x)
{
    cot = 0;
    num = x;
}

Better yet, since cot is always going to be 0 at construction, just set cot to 0 as a private variable like this:

class ulam
{
   int num;
   double prod;
   int cot = 0;
public:
  //....
};

This means that you could still have a default constructor that will do nothing, and the one that takes an integer won't require cot to be set to 0.

Second Problem

Your second problem is that the loop condition is wrong. It should be num != 1, not num == 1. num == 1 would be the loop would never run unless 1 was passed in cin.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88