2
static void collatz(int i)
{
    int x=0,a=0,res=0,count=0;
    int array[50];
    array[0]=i;
    while(array[count]!=0)
    {
        if(array[count]%2==0)
        {
            count++;
            array[count]=i/2;
        }
        else
        {
            count++;
            array[count]=3*array[count-1]-1;
        }
    }
}
int main()
{
    int a;
    scanf("%d",&a);
    collatz(a);
    system("pause");
    return 0;
}

When I compile and run the code, I enter 8 as "a" and console crushes itself. I'm using dev c. Sorry for my awful english but I hope I'm clear enough.

Benesh
  • 3,398
  • 1
  • 18
  • 38

2 Answers2

0

I count four errors:

  • The loop should terminate when array[count] is 1, not 0
  • You should check that count is less than 49
  • array[count]=i/2 should be array[count]=array[count-1]/2
  • array[count]=3*array[count-1]-1 should be array[count]=3*array[count-1]+1

So the code with these issues fixed, and some slight shortening, could be:

static void collatz(int i) {
    int count=0;
    int array[50];
    array[0]=i;
    while (count < 49) {
        int j = array[count++];
        if (j == 1)
           break;
        else if(j % 2 == 0)
            array[count]=j/2;
        else
            array[count]=3*j+1;
    }
}
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
0

first, the while loop is wrong, you should end the while when array[count] == 1, so you can use while(array[count] > 1) to test.

second, array[count]=i/2; is wrong, you shuld use array[count]=array[count-1]/2;.

Third, you should check the count < 50, because you declare int array[50];.

static void collatz(int i) 
{
    int x=0,a=0,res=0,count=0;
    int array[50]= {0};
    array[0]=i;
    while(array[count] > 1 && count < 50)
    {
        if(array[count]%2==0)
        {
            count++;
            array[count]=array[count-1]/2;
        }
        else
        {
            count++;
            array[count]=3*array[count-1]-1;
        }
    }
}
BlackMamba
  • 10,054
  • 7
  • 44
  • 67