Search code examples
cfunctionrecursionconditional-statementsfunction-definition

Why is my code not dividing inside of the function?


I want to create a hailstone sequence using recursive function. But the even number is not getting divided, I want to know where and what did I do wrong?

#include <stdio.h>

int sequence(int n);

int main()
{
    int n = 0;
    printf("\nEnter a number: ");
    scanf("%d", &n);
    printf("\nThe sequence is as follows:");
    sequence(n);
    return 0;
}

int sequence(int n)
{
    printf("%d\t ", n);

    if (n == 1) {
        return 0;
    } else if (n % 2 == 0) {
        n = n / 2;
    } else {
        return n = sequence(n * 3 + 1);
    }
}

Solution

  • The function does nothing in this else statement

    else if (n % 2 == 0)
    {
        n = n / 2;
    }
    

    Define the function at least like

    int sequence(int n)
    {
        printf("%d\t ", n);
    
        if (n == 1)
        {
            return 0;
        }
        else
        {
            return sequence( n % 2 == 0 ? n / 2 :  n * 3 + 1 );
        }
    }
    

    Though it seems the return type of the function does not make a sense. So the function can be defined like

    void sequence(int n)
    {
        printf("%d\t ", n);
    
        if ( n != 1 )
        {    
            sequence( n % 2 == 0 ? n / 2 :  n * 3 + 1 );
        }
    }