0

I recognize this is a common theme, but I cannot find what I am looking for in my own code, somewhat making all other answers moot if I cannot find what's wrong.

I have to implement Collatz recursion for whatever value the user is queried for, and then return the number of steps (iterations) it takes for that number to reach one.

int main(void)
{
    int m,n,count;
    printf("Enter a value for 'n': ");
    scanf("%d",&n);

    m = n;
    count = 0;
    if (m != 1) {
        if (m%2 == 0); {
            m = m/2;
            count++;
            }

        if (m%2 == 1) {
            m = m*3+1;
            count++;
            }
        }

    if (m==1)
        return count;

    printf("The number %d takes %d iterations to reach '1'",n,count);

    return 0;
}

Any advice would be wonderful. My belief was that this code (if (m != 1)) would return a new m value each time, and each time it did, it would add to count.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
yup
  • 1
  • 6
  • 3
    You should probably use `else` instead of `if (m % 2 == 1)`; you do one or the other, but you don't do both (because if the value of `m` is 2 at the start, your `if (m % 2 == 0)` code sets `m` to 1, and then the `if (m % 2 == 1)` code sets it to 4, and … you would have problems. You need a loop (`while (m != 1)`) instead of an `if` too. Otherwise, you only make one iteration. Finally, there's no recursion in sight here. – Jonathan Leffler Mar 31 '15 at 03:27
  • 2
    Watch out for that semicolon after your if condition. You probably don't want that there. – Carl Norum Mar 31 '15 at 03:32
  • 1
    the returned value (not the variable being set) for calls scanf() and family, should always be checked to assure the operation was successful. In this case should also check the value of 'n' to assure it is greater than 1 – user3629249 Mar 31 '15 at 04:42
  • 1
    the variable 'count' will always be 0 or 1 or 2. That is probably not what you want. I suspect the code needs to have loop, probably: while( 1 != m ) The posted code fails to check for an input that is 0 or negative and handle such input errors – user3629249 Mar 31 '15 at 04:51
  • 2
    BTW: There is no recursion in the posted code – user3629249 Mar 31 '15 at 04:52

0 Answers0